Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. class Program
  2. {
  3. static void DoIt(string entry)
  4. {
  5. Console.WriteLine("Message: " + entry);
  6. }
  7.  
  8. static async void DoIt2(string entry)
  9. {
  10. await Task.Yield();
  11. Console.WriteLine("Message2: " + entry);
  12. }
  13.  
  14. static void Main(string[] args)
  15. {
  16. // old way
  17. Action<string> async = DoIt;
  18. async.BeginInvoke("Test", ar => { async.EndInvoke(ar); ar.AsyncWaitHandle.Close(); }, null);
  19. Console.WriteLine("old-way main thread invoker finished");
  20. // new way
  21. DoIt2("Test2");
  22. Console.WriteLine("new-way main thread invoker finished");
  23. Console.ReadLine();
  24. }
  25. }
  26.  
  27. Task.Run(A);
  28.  
  29. static async void FireAndForget(this Task task)
  30. {
  31. try
  32. {
  33. await task;
  34. }
  35. catch (Exception e)
  36. {
  37. // log errors
  38. }
  39. }
  40.  
  41. MyTaskAsyncMethod().FireAndForget();
  42.  
  43. Task.Factory.StartNew(() => DoIt2("Test2"))
  44.  
  45. public async void Method()
  46. {
  47. //Do UI stuff
  48. await SomeTaskAsync();
  49. //Do more UI stuff (as if called via Invoke from a thread)
  50. var nextTask = NextTaskAsync();
  51. //Do UI stuff while task is running (as if called via BeginInvoke from a thread)
  52. await nextTask;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement