There is a pattern that allows to cache [StringBuilder] instance per thread, using the [ThreadStaticAttribute]. I wonder if it's safe to cache when asynchronous code is used. I mean after the async part is completed, the continuation may start in another thread and the cached [StringBuilder] will be corrupted
Asked
Active
Viewed 28 times
0
-
1It's often a good idea to also share the code in front of which you are thinking. – Sinatr Feb 10 '21 at 09:44
-
1https://stackoverflow.com/a/13010688/613130 The response of Marc Gravell was to not play with `ThreadStatic` and `async` – xanatos Feb 10 '21 at 09:46
-
1you should not use `ThreadStaticAttribute` in async context, use [`AsyncLocal
`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.asynclocal-1?view=net-5.0) at least. – Guru Stron Feb 10 '21 at 09:47 -
Microsoft.Extensions.ObjectPool has special detection for string builder/custom cached pool. You might consider using that rather than building your own. It's designed for aspnet.core but you can use it anywhere. It's async safe, mainly because it's up to you to return the object to the pool/cache – pinkfloydx33 Feb 10 '21 at 12:08