Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading.Tasks;
- class Program
- {
- static void Main(string[] args)
- {
- TestAsync();
- Console.WriteLine($"{now()}: Before ReadKey()");
- Console.ReadKey();
- }
- static async Task<int> AsyncTask()
- {
- Console.WriteLine($"{now()}: AsyncTask() start");
- await Task.Delay(2000);
- Console.WriteLine($"{now()}: AsyncTask() end");
- //DoInvalidAction();
- return new Random().Next(1,10);
- }
- static void DoInvalidAction() => throw new Exception("test exception");
- static void TestAsync()
- {
- Console.WriteLine($"{now()}: TestAsync() start");
- var _task = AsyncTask();
- _task.GetAwaiter().OnCompleted(() => OnTaskCompleted(_task, "AsyncTask"));
- Console.WriteLine($"{now()}: TestAsync() end");
- }
- static async void OnTaskCompleted(Task<int> task, object callee)
- {
- try
- {
- Console.WriteLine($"{now()}: '{callee}' task completed! result: {await task}");
- }
- catch (Exception ex) when (LogException(ex, true))
- {
- //LogException(ex);
- }
- }
- static string now() => DateTime.Now.ToString("mm:ss.ffff");
- static bool LogException(Exception ex, bool suppress) { Console.WriteLine(ex); return !suppress; }
- }
Advertisement
Add Comment
Please, Sign In to add comment