Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. async void Form1_Load(object sender, EventArgs e)
  2. {
  3. // on the UI thread
  4. Debug.WriteLine(new { where = "before",
  5. Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread });
  6.  
  7. var tcs = new TaskCompletionSource<bool>();
  8.  
  9. this.BeginInvoke(new MethodInvoker(() => tcs.SetResult(true)));
  10.  
  11. await tcs.Task.ContinueWith(t => {
  12. // still on the UI thread
  13. Debug.WriteLine(new { where = "ContinueWith",
  14. Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread });
  15. }, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);
  16.  
  17. // on a pool thread
  18. Debug.WriteLine(new { where = "after",
  19. Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread });
  20. }
  21.  
  22. await
  23.  
  24. await Task.Delay(100).ContinueWith(t =>
  25. {
  26. // on a pool thread
  27. Debug.WriteLine(new { where = "ContinueWith",
  28. Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread });
  29. }, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);
  30.  
  31. ConfiguredTaskAwaitable
  32.  
  33. class DumbSyncContext: SynchronizationContext
  34. {
  35. }
  36.  
  37. // ...
  38.  
  39. Debug.WriteLine(new { where = "before",
  40. Thread.CurrentThread.ManagedThreadId,
  41. Thread.CurrentThread.IsThreadPoolThread });
  42.  
  43. var tcs = new TaskCompletionSource<bool>();
  44.  
  45. var thread = new Thread(() =>
  46. {
  47. Debug.WriteLine(new { where = "new Thread",
  48. Thread.CurrentThread.ManagedThreadId,
  49. Thread.CurrentThread.IsThreadPoolThread});
  50. SynchronizationContext.SetSynchronizationContext(new DumbSyncContext());
  51. tcs.SetResult(true);
  52. Thread.Sleep(1000);
  53. });
  54. thread.Start();
  55.  
  56. await tcs.Task.ContinueWith(t => {
  57. Debug.WriteLine(new { where = "ContinueWith",
  58. Thread.CurrentThread.ManagedThreadId,
  59. Thread.CurrentThread.IsThreadPoolThread});
  60. }, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);
  61.  
  62. Debug.WriteLine(new { where = "after",
  63. Thread.CurrentThread.ManagedThreadId,
  64. Thread.CurrentThread.IsThreadPoolThread });
  65.  
  66. SynchronizationContext
  67.  
  68. await FooAsync().ConfigureAwait(false);
  69.  
  70. static Task FooAsync(bool runSync)
  71. {
  72. if (!runSync)
  73. await Task.Delay(100);
  74. }
  75.  
  76. await FooAsync(true).ConfigureAwait(false);
  77.  
  78. await task.ConfigureAwait(false);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement