Advertisement
wingman007

AsyncAwaitConsole

Nov 4th, 2019
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4.  
  5. namespace AsyncAwaitConsole
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             // What are Async and Await ( .NET 4.5 Interview question with answers)?
  12.             // https://www.youtube.com/watch?v=V2sMXJnDEjM
  13.             // Async Await are markers showing where the control resumes after the task or thread completes
  14.  
  15.             Method(); // only method will wait for the LongTask to complete
  16.             Console.WriteLine("Main thread"); // the main thread is executed
  17.             Console.ReadLine();
  18.         }
  19.  
  20.         public static async void Method() // You have to use async if you use await
  21.         {
  22.             await Task.Run(new Action(LongTask)); // invoces LongTask in paralel mode
  23.             // but what we want is actully to execute the next line only when LongTask is finished.
  24.             Console.WriteLine("New Thread"); // Wait until the long task finishes
  25.         }
  26.  
  27.         public static void LongTask()
  28.         {
  29.             Thread.Sleep(20000);
  30.         }
  31.     }
  32. }
  33.  
  34. /*
  35.  Main thread
  36. New Thread
  37. dasd
  38.      */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement