How can explore async and await keywords?

Async and Await keywords used for asynchronous programming in C#.

Example:

static void Main(string[] args)
{
Method1();
Console.WriteLine("Main Thread");
Console.ReadLine();
}
public static void Method1()
{
Task.Run(new Action(Method2));
Console.WriteLine("New Thread");
}
public static void Method2()
{
Thread.Sleep(10000);
}

  1. Method1() gets called from the main thread.
  2. Method1() spawns a Task named Method2() which waits for 10 seconds.
  3. Same time the control comes back to Method1() to execute the remaining code after the task called. While Method2() waits for 10 seconds the remaining code of Method1() get’s executed.
Now let’s modify the algorithm to use async and await. All other thing remains same except Method1().

public static async void Method1()
{
await Task.Run(new Action(Method2));
Console.WriteLine("New Thread");
}

Now, the step 2 in our last try run will only continue execution once step 2 completed its execution.
You can also achieve the same with Task.Wait and Task.ContinueWith but Task.Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. Await will asynchronously wait until the task completes. This means the current method is “paused” (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

Need Help? Contact Us.

Log in

*
*

Forgot password?

*

New User

*
*
*
*