Advertisement
Guest User

Untitled

a guest
Aug 4th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4.  
  5. class AsyncLocal
  6. {
  7. static AsyncLocal<string> _asyncLocalString = new AsyncLocal<string>();
  8. static ThreadLocal<string> _threadLocalString = new ThreadLocal<string>();
  9.  
  10. static async Task AsyncMethodA()
  11. {
  12. // Start multiple async method calls, with different AsyncLocal values.
  13. // We also set ThreadLocal values, to demonstrate how the two mechanisms differ.
  14. _asyncLocalString.Value = "Value 1";
  15. _threadLocalString.Value = "Value 1";
  16. var t1 = AsyncMethodB("Value 1");
  17.  
  18. _asyncLocalString.Value = "Value 2";
  19. _threadLocalString.Value = "Value 2";
  20. var t2 = AsyncMethodB("Value 2");
  21.  
  22. // Await both calls
  23. await t1;
  24. await t2;
  25. }
  26.  
  27. static async Task AsyncMethodB(string expectedValue)
  28. {
  29. Console.WriteLine($"Entering AsyncMethodB. Expected '{expectedValue}', AsyncLocal value is '{_asyncLocalString.Value}, ThreadLocal value is '{_threadLocalString.Value}'");
  30. await Task.Delay(100);
  31. Console.WriteLine($"Exiting AsyncMethodB. Expected '{expectedValue}', got '{_asyncLocalString.Value}, ThreadLocal value is '{_threadLocalString.Value}'");
  32. }
  33.  
  34. static void Main(string[] args)
  35. {
  36. AsyncMethodA().Wait();
  37. }
  38. }
  39.  
  40. /*
  41. The output should be:
  42.  
  43. Entering AsyncMethodB. Expected 'Value 1', AsyncLocal value is 'Value 1, ThreadLocal value is 'Value 1'
  44. Entering AsyncMethodB. Expected 'Value 2', AsyncLocal value is 'Value 2, ThreadLocal value is 'Value 2'
  45. Exiting AsyncMethodB. Expected 'Value 2', got 'Value 2, ThreadLocal value is ''
  46. Exiting AsyncMethodB. Expected 'Value 1', got 'Value 1, ThreadLocal value is ''
  47. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement