Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async/await #26

Open
Henrik-Xu opened this issue May 27, 2019 · 0 comments
Open

async/await #26

Henrik-Xu opened this issue May 27, 2019 · 0 comments

Comments

@Henrik-Xu
Copy link
Owner

Henrik-Xu commented May 27, 2019

async/await

  • 1.C#5.0 中引入了asyncawait。这两个关键字可以让我们更加轻松的完成异步代码的编写。

  • 2.方法(包括Lambada表达式和匿名方法)可以用async关键字标记,允许该方法以非阻塞的形式进行

工作。

  • 3.用async关键字的方法(包括Lambada表达式和匿名方法)在遇到await关键字之前将以阻塞的形式

运行。

  • 4.单个async可以拥有多个await上下文

  • 5.当遇到await表达式时,调用线程将挂起,直到await的任务完成。同时,控制将返回返回给方法的

调用者。

  • 6.await关键字将从视图中隐藏返回的Task对象,直接返回实际的返回值。没有返回值的方法可以简单

的返回void

  • 7.根据命名约定,要被异步调用的方法应该以Async作为后缀。
static void Main(string[] args)
{
  string txt = DoWorkAsync().Result;
  Console.WriteLine("main threadId=" + Thread.CurrentThread.ManagedThreadId);

  Console.Read();
}
public static async Task<string> DoWorkAsync()
{
  return await Task.Run(()=>
  {
    Console.WriteLine("child threadId=" + Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(1000);
    return "Done with work!";
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant