1、创建任务:
同步方法:
static string Greeting(string name)
{
Console.WriteLine("running greeting in thread {0} and task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
Thread.Sleep(3000);
return string.Format("Hello, {0}", name);
}
定义方法GreetingAsync,使方法异步化。基于任务的异步模式指定在异步方法名上加上Async作为后缀,并返回一个任务。
static Task<string> GreetingAsync(string name)
{
return Task.Run<string>(() =>
{
Console.WriteLine("running greetingasync in thread {0} and task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
return Greeting(name);
});
}
2、调用异步方法:
可以使用关键字await关键字来调用返回任务的异步方法GreetingAsync。使用await关键字需要有用async修饰符声明的方法。
private async static void CallerWithAsync()
{
Console.WriteLine("started CallerWithAsync in thread {0} and task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
string result = await GreetingAsync("Stephanie");
Console.WriteLine(result);
Console.WriteLine("finished GreetingAsync in thread {0} and task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
}
输出结果: