Transferring Data Between ThreadPool Threads

I have a C # web server that I have profiled using the StackOverflow mini filter. Since this is not an ASP.NET server, but each request was usually executed in its own thread, I linked the miniprofile to using the ThreadStatic repository to track all the profilers of the incoming request from beginning to end. It works well.

Recently, we have converted everything to use async/await , which means that continuations after await usually do not return to the same Thread and therefore the ThreadStatic repository no longer works.

What is the best way to transfer a small piece of data between different ThreadPool threads in this case? Are there existing SynchronizationContext implementations that would be useful for something like this?

+8
multithreading c # async-await miniprofiler
source share
1 answer

What is the best way to transfer a small piece of data between ThreadPool threads in this case?

Using the context of a logical call through the CallContext class. It provides two static methods: LogicalSetData and LogicalGetData . The call context is saved and marshaled through the ExecutionContext , which is also responsible for the synchronization context, etc.

Using this class has two limitations:

  • You are limited to using .NET 4.5 and higher

  • The boolean context uses copy-on-write semantics and performs a shallow copy after data changes. This means that you should only use immutable data, as links can be shared between multiple threads.

CallContext final note: CallContext initialized only after it is called. This means that when you use it, you get some overhead due to copy to write.

More on what can be found in the post from Stephan Cleary is called Implicit Asynchronous Context.

+8
source share

All Articles