axuno / SmartFormat

A lightweight text templating library written in C# which can be a drop-in replacement for string.Format
Other
1.1k stars 105 forks source link

SmartFormat and async code #274

Closed berhir closed 2 years ago

berhir commented 2 years ago

I have a question about using SmartFormat with async code. The documentation states that SmartFormat is not thread safe by default.

As far as I understand, when we use async, the code runs on different threads from the thread pool. Does it mean that we must always set SmartSettings.IsThreadSafeMode = true when we use SmartFormat in async code?

In modern .NET everything seems to be async. Especially in ASP.NET Core, everything must be async to avoid blocking other request.

Do I understand this correctly? And if yes, wouldn't it be better to enable the thread safe mode by default and disable it for the (rare?) cases where only one single thread is involved?

Thank you!

axunonb commented 2 years ago

Hi Bernd, Yes, it is like you describe. SmartSettings.IsThreadSafeMode = true must be set, and the static Smart.Format(...) can't be used, On each thread a new SmartFormatter must be created. See more comments here. Indeed, we considered making thread-safe the default, but didn't implement because of the impact on performance, which was a major target of v3. Still, this could be revised in a future version.

berhir commented 2 years ago

Thank you for the quick reply and the explanation.

I read the documentation before we started to use SmartFormat and thought that we are not affected by this, as we don't use multiple threads explicitly. But then we faced the same exceptions as in #273 and the message was not really helpful. Now it's clear and we were able to fix it.

But still, I guess many people will run into this problem. I understand your focus on performance, but maybe you can mention async programming explicitly in the documentation. And maybe even on the main readme page, as I expect a lot of people will not read the documentation ;)

axunonb commented 2 years ago

async is now explicitly mentioned: Async and Thread Safety

berhir commented 2 years ago

Great, thank you!

axunonb commented 2 years ago

@berhir We just published release v3.1.0: