Kaneboy
Links: https://www.zhihu.com/question/50779566/answer/123137983
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
In simple terms, ExecutionContext is the current execution context. You can assume that the CLR will automatically do the following (pseudo-code) when you switch threads in a contemporary code:
var oldEc = ExecutionContext.Capture();ThreadPool.QueueUserWorkItem(() => { ExecutionContext.Run(oldEc, () => { // 这里才是用户真正需要在另外线程执行代码 });});
That is, whether the user is using a traditional asynchronous delegate (Delegate.begininvoke ()), ThreadPool.QueueUserWorkItem (), or Task.run (), The CLR guarantees that the current executioncontext will be captured at the bottom, and then continue executing the subsequent code on the other thread, based on the captured ExecutionContext.
The purpose of this is to be able to save some context data on the original thread, such as the custom data stored in CallContext through Logicalsetdata (), and the credential data stored by the user on the SecurityContext. Passed to subsequent threads, allowing subsequent threads to take advantage of those data. This data can be correctly passed (logically) in accordance with the logical flow of asynchronous code, rather than the actual execution process of the code.
The. NET 4.6 New Asynclocal<t> class (https://msdn.microsoft.com/en-us/library/dn906268 (v=vs.110). aspx ), the reason that "Local" data can be saved between asynchronous operations is to do so by using the ExecutionContext to maintain the flow between threads. (asynclocal<t> Source Code reference:https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/system/ threading/asynclocal.cs/#L41)
Of course, in most scenarios, with the advent of the Asynclocal<t> class, developers no longer need to use Callcontext.logicalsetdata ()/logicalgetdata () directly, It would be nice to use the asynclocal<t> directly. It's more intuitive.
and the Asynclocal<t> class "opposite", is the Threadlocal<t> class. Threadlocal<t> is to maintain a different version for each of the different threads, acting like [threadstatic].
Finally found the main question also asked the ExecutionContext and AppDomain relationship, according to my understanding, ExecutionContext is mainly a thread-based Dongdong, and the AppDomain should have no relationship.
. NET in ExecutionContext