Kermer

Async example

Nov 19th, 2018
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. using System;
  2. using System.Threading.Tasks;
  3.  
  4. class Program
  5. {
  6.     static void Main(string[] args)
  7.     {
  8.         TestAsync();
  9.        
  10.         Console.WriteLine($"{now()}: Before ReadKey()");
  11.         Console.ReadKey();
  12.     }
  13.  
  14.     static async Task<int> AsyncTask()
  15.     {
  16.         Console.WriteLine($"{now()}: AsyncTask() start");
  17.         await Task.Delay(2000);
  18.         Console.WriteLine($"{now()}: AsyncTask() end");
  19.         //DoInvalidAction();
  20.         return new Random().Next(1,10);
  21.     }
  22.     static void DoInvalidAction() => throw new Exception("test exception");
  23.  
  24.     static void TestAsync()
  25.     {
  26.         Console.WriteLine($"{now()}: TestAsync() start");
  27.         var _task = AsyncTask();
  28.         _task.GetAwaiter().OnCompleted(() => OnTaskCompleted(_task, "AsyncTask"));
  29.         Console.WriteLine($"{now()}: TestAsync() end");
  30.     }
  31.  
  32.     static async void OnTaskCompleted(Task<int> task, object callee)
  33.     {
  34.         try
  35.         {
  36.             Console.WriteLine($"{now()}: '{callee}' task completed! result: {await task}");
  37.         }
  38.         catch (Exception ex) when (LogException(ex, true))
  39.         {
  40.             //LogException(ex);
  41.         }
  42.     }
  43.  
  44.     static string now() => DateTime.Now.ToString("mm:ss.ffff");
  45.     static bool LogException(Exception ex, bool suppress) { Console.WriteLine(ex); return !suppress; }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment