Created
July 17, 2015 20:57
-
-
Save richlander/2a3e3338b7b170735c57 to your computer and use it in GitHub Desktop.
AsyncLocal<T> sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
class AsyncLocal | |
{ | |
static AsyncLocal<string> _asyncLocalString = new AsyncLocal<string>(); | |
static ThreadLocal<string> _threadLocalString = new ThreadLocal<string>(); | |
static async Task AsyncMethodA() | |
{ | |
// Start multiple async method calls, with different AsyncLocal values. | |
// We also set ThreadLocal values, to demonstrate how the two mechanisms differ. | |
_asyncLocalString.Value = "Value 1"; | |
_threadLocalString.Value = "Value 1"; | |
var t1 = AsyncMethodB("Value 1"); | |
_asyncLocalString.Value = "Value 2"; | |
_threadLocalString.Value = "Value 2"; | |
var t2 = AsyncMethodB("Value 2"); | |
// Await both calls | |
await t1; | |
await t2; | |
} | |
static async Task AsyncMethodB(string expectedValue) | |
{ | |
Console.WriteLine($"Entering AsyncMethodB. Expected '{expectedValue}', AsyncLocal value is '{_asyncLocalString.Value}, ThreadLocal value is '{_threadLocalString.Value}'"); | |
await Task.Delay(100); | |
Console.WriteLine($"Exiting AsyncMethodB. Expected '{expectedValue}', got '{_asyncLocalString.Value}, ThreadLocal value is '{_threadLocalString.Value}'"); | |
} | |
static void Main(string[] args) | |
{ | |
AsyncMethodA().Wait(); | |
} | |
} | |
/* | |
The output should be: | |
Entering AsyncMethodB. Expected 'Value 1', AsyncLocal value is 'Value 1, ThreadLocal value is 'Value 1' | |
Entering AsyncMethodB. Expected 'Value 2', AsyncLocal value is 'Value 2, ThreadLocal value is 'Value 2' | |
Exiting AsyncMethodB. Expected 'Value 2', got 'Value 2, ThreadLocal value is '' | |
Exiting AsyncMethodB. Expected 'Value 1', got 'Value 1, ThreadLocal value is '' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this work in asp.net also? wcf?