首页 > 代码库 > c# async

c# async

• Methods (as well as lambda expressions or anonymous methods) can be marked with the async keyword to enable the method to do work in a nonblocking manner.
• Methods (as well as lambda expressions or anonymous methods) marked with the async keyword will run in a blocking manner until the await keyword is encountered.
• A single async method can have multiple await contexts.
• When the await expression is encountered, the calling thread is suspended until the awaited task is complete. In the meantime, control is returned to the caller of the method.
• The await keyword will hide the returned Task object from view, appearing to directly return the underlying return value. Methods with no return value simply return void.
• As a naming convention, methods that are to be called asynchronously should be marked with the “Async” suffix.

Call the async methode, get the task object and await later:

Task<string> ts = WorkAsync();//Do some independent work ...//now wait for WorkAsync tb.Text = await ts;

 
await with timeuot <1>:

if (await Task.WhenAny(task, Task.Delay(delay)) == task){ ... }else { //timeout  ... }