C# 异步编程笔记

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);
}

输出结果:

C# 异步编程笔记

 

C# 异步编程笔记

上一篇:C# IIS HTTP 错误 500.21 - Internal Server Error 处理程序“PageHandlerFactory-Integr


下一篇:C#开发中常用的加密解密方法