13

I know that when you run some method in parallel by calling BeginInvoke() or ThreadPool.QueueUserWorkItem(...) .NET framework is capturing ExecutionContext object that contains Code Access Security information and some other things.

What I want, is to include in ExecutionContext some data that is needed by my parallel method, but must be also captured at the moment of queuing the task.

Problem is that not always I do have control on the code that is creating this parallel task, so I must find a way to store this data before I call this external code. Thats why I thought about ExecutionContext class.

Is there any way to pass some state the parallel task when I'm not always in the control of the code that is splitting the work between threads.

Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
SeeR
  • 2,158
  • 1
  • 20
  • 35

3 Answers3

15

Found it:

CallContext.LogicalSetData(...)

(documentation)

and

CallContext.LogicalGetData(...)

(documentation)

Milan Gardian
  • 11,326
  • 5
  • 38
  • 45
SeeR
  • 2,158
  • 1
  • 20
  • 35
1

You can use AsyncLocal<T> for storing values that will propagate with the exection context.

Example:

var myLocal = new AsyncLocal<string> { Value = "My value" };

ThreadPool.QueueUserWorkItem(_ => { Console.WriteLine("Value: " + myLocal.Value); });

ExecutionContext.SuppressFlow();
ThreadPool.QueueUserWorkItem(_ => { Console.WriteLine("Value without flowing execution context: " + myLocal.Value); });
ExecutionContext.RestoreFlow();

// Output:
// Value: My value
// Value without flowing execution context:

See the documentation for more information.

The Slicer
  • 509
  • 1
  • 4
  • 9
0

I don't know how it relates to ExecutionContext, but back in the day, we could create context-bound objects. See Context class. Ignore the fact that this particular class is for infrastructure - the article is a starting point to learn about contexts.

John Saunders
  • 160,644
  • 26
  • 247
  • 397