I'm looking for an execution context which plays nicely with async/await
and with the TPL at the same time in the following way (expected behavior):
async Task<string> ReadContext(string slot)
{
// Perform some async code
...
return Context.Read(slot);
}
(1) Playing nicely with async/await
Context.Store("slot", "value");
await DoSomeAsync();
Assert.AreEqual("value", Context.Read("slot"));
Context.Store("slot", "value");
var value = await ReadContext("slot");
Assert.AreEqual("value", value);
(2) Playing nicely with Task.Run()
Context.Store("slot", "value");
var task = Task.Run(() => ReadContext("slot"));
Assert.IsNull(task.Result);
(3) Playing nicely with an awaited Task
Context.Store("slot", "value");
var value = await Task.Run(() => ReadContext("slot"));
Assert.AreEqual("value", value);
(3) is not essential but would be nice. I use CallContext
now but it fails at (2) as the values stored in it are accessible even in manually ran tasks, even in those ran using Task.Factory.StartNew(..., LongRunning)
which should enforce running the task on a separate thread.
Is there any way to accomplish that?