Can someone please explain async / wait?

I'm starting to learn about async / await in C # 5.0, and I don’t get it at all. I do not understand how it can be used for parallelism. I tried the following very basic program:

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Task task1 = Task1(); Task task2 = Task2(); Task.WaitAll(task1, task2); Debug.WriteLine("Finished main method"); } public static async Task Task1() { await new Task(() => Thread.Sleep(TimeSpan.FromSeconds(5))); Debug.WriteLine("Finished Task1"); } public static async Task Task2() { await new Task(() => Thread.Sleep(TimeSpan.FromSeconds(10))); Debug.WriteLine("Finished Task2"); } } } 

This program simply blocks when Task.WaitAll() called and never ends. Can someone please explain to me why? I'm sure I just missed something simple or just don't have the right mental model for it, and none of the MSDN blogs or articles that are there helps.

+46
c # async-await
Jan 6 '13 at 0:13
source share
4 answers

I recommend that you start from intro to async / await and follow the official MSDN TAP documentation .

As I mentioned in my blog blog, there are several Task members who are delays with TPL and do not use pure async code. new Task and Task.Start should be replaced with Task.Run (or TaskFactory.StartNew ). Similarly, Thread.Sleep should be replaced with Task.Delay .

Finally, I recommend that you not use Task.WaitAll ; your console application should just Wait on one Task that uses Task.WhenAll . With all these changes, your code will look like this:

 class Program { static void Main(string[] args) { MainAsync().Wait(); } public static async Task MainAsync() { Task task1 = Task1(); Task task2 = Task2(); await Task.WhenAll(task1, task2); Debug.WriteLine("Finished main method"); } public static async Task Task1() { await Task.Delay(5000); Debug.WriteLine("Finished Task1"); } public static async Task Task2() { await Task.Delay(10000); Debug.WriteLine("Finished Task2"); } } 
+47
Jan 06 '13 at 1:19
source share

Your tasks never end because they never start.

I would Task.Factory.StartNew create a task and run it.

 public static async Task Task1() { await Task.Factory.StartNew(() => Thread.Sleep(TimeSpan.FromSeconds(5))); Debug.WriteLine("Finished Task1"); } public static async Task Task2() { await Task.Factory.StartNew(() => Thread.Sleep(TimeSpan.FromSeconds(10))); Debug.WriteLine("Finished Task2"); } 

As a side note, if you're really just trying to pause the asynchronous method, there is no need to block the entire thread, just use Task.Delay

 public static async Task Task1() { await Task.Delay(TimeSpan.FromSeconds(5)); Debug.WriteLine("Finished Task1"); } public static async Task Task2() { await Task.Delay(TimeSpan.FromSeconds(10)); Debug.WriteLine("Finished Task2"); } 
+10
Jan 06 '13 at 0:21
source share

Async and wait for markers that mark the position of the code from which the control should resume after the task (thread) has completed. Here's a detailed youtube video that explains the concept in a defiant way http://www.youtube.com/watch?v=V2sMXJnDEjM

If you want, you can also read this coodeproject article, which explains this in a more visual way. http://www.codeproject.com/Articles/599756/Five-Great-NET-Framework-4-5-Features#Feature1:- "Async" and "Await" (Codemarkers)

+7
Sep 23 '13 at 18:51
source share

Understand C # task, asynchronously and wait

C # task

A task class is an asynchronous shell of a task. Thread.Sleep (1000) can stop a thread running for 1 second. Although Task.Delay (1000) will not stop the current operation. See Code:

 public static void Main(string[] args){ TaskTest(); } private static void TaskTest(){ Task.Delay(5000); System.Console.WriteLine("task done"); } 

When you start, "job completed" will be displayed immediately. Therefore, I can assume that each method from Task should be asynchronous. If I replace TaskTest () with Task.Run (() => TaskTest ()), the completed task will not be displayed at all until I add the console. ReadLine (); after the Run method.

Internally, the Task class represents the state of a thread in a state machine. Each state in the state machine has several states, such as “Start”, “Delay”, “Cancel” and “Stop”.

asynchronous and pending

Now you may wonder if all tasks are asynchronous, what is the purpose of Task.Delay? next, let it really delay the current thread using async and wait

 public static void Main(string[] args){ TaskTest(); System.Console.WriteLine("main thread is not blocked"); Console.ReadLine(); } private static async void TaskTest(){ await Task.Delay(5000); System.Console.WriteLine("task done"); } 

async tell caller, I'm an asynchronous method, don't wait for me. waiting inside TaskTest () requires waiting for an asynchronous task. Now, after starting, the program will wait 5 seconds to display the completed text.

Cancel task

Since Task is a state machine, there must be a way to cancel the task while the task is executing.

 static CancellationTokenSource tokenSource = new CancellationTokenSource(); public static void Main(string[] args){ TaskTest(); System.Console.WriteLine("main thread is not blocked"); var input=Console.ReadLine(); if(input=="stop"){ tokenSource.Cancel(); System.Console.WriteLine("task stopped"); } Console.ReadLine(); } private static async void TaskTest(){ try{ await Task.Delay(5000,tokenSource.Token); }catch(TaskCanceledException e){ //cancel task will throw out a exception, just catch it, do nothing. } System.Console.WriteLine("task done"); } 

Now that the program is running, you can enter “stop” to cancel the “Delay” task.

+4
Sep 08 '16 at 3:37
source share



All Articles