4

Update:

Found similar question.

I want to implement some services following AmbientContext design pattern for our ASP.NET application.
For example I need user name (like Thread.CurrentPrincipal) to be set once at the very beginning of the request processing and flow between threads when async operations are performed.
Thus I need to attach data to ExecutionContext and then detach it when request is processed.

Unfortuantely, I have no idea, how to do it.

There is only a small hint in documentation:

Internally, the ExecutionContext stores all data that is associated with the LogicalCallContext. This allows the LogicalCallContext data to be propagated when the ExecutionContext is copied and transferred.

Community
  • 1
  • 1
Pavel Voronin
  • 11,811
  • 6
  • 54
  • 113
  • Being non the wiser as to the difference between a SynchronisationContext (which I was going to suggest making use of) and ExecutionContext I arrived here via google: http://blogs.msdn.com/b/pfxteam/archive/2012/06/15/executioncontext-vs-synchronizationcontext.aspx – brumScouse Jun 02 '14 at 12:58
  • @brumScouse Exactly from this article I came to the conclusion that ExecutionContext is more appropriate being a more general thing than SynchronizationContext. – Pavel Voronin Jun 02 '14 at 13:09
  • @brumScouse the only thing I had to do to get the answer is to read comments under the article =) – Pavel Voronin Jun 02 '14 at 13:40
  • Maybe I should have read a bit more in depth! Nice one, I'll read those with interest. – brumScouse Jun 02 '14 at 16:41

1 Answers1

2

I had the same question. I eventually found the CallContext class, which can do this using the LogicalGetData and LogicalSetData methods. Here's a very good article with examples that discusses how to use this class.

JSBձոգչ
  • 38,721
  • 16
  • 95
  • 160
  • Yes, I saw Stephen's article after I eventually wrote my own but very similar implementation. – Pavel Voronin Apr 12 '16 at 12:02
  • Make sure to use LogicalSetData/LogicalGetData to preserve data between async calls (e.g. when you call database or API)- https://docs.microsoft.com/en-us/dotnet/api/system.runtime.remoting.messaging.callcontext?redirectedfrom=MSDN&view=netframework-4.7.2 – Sergii Shumakov Sep 04 '18 at 15:12