.NET 4.0推出了新一代的多线程模型Task。async/await特性是与Task紧密相关的,所以在了解async/await前必须充分了解Task的使用。
//多线程例子
private async void button_Click(object sender, EventArgs e)
{
var client = new WebClient();
var result = await client.DownloadStringTaskAsync("https://www.pb2.cn");
textBox1.Text = result;
MessageBox.Show("Complete");
}
Async/Await/Task的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DemoAsync
{
class Program
{
static void Main(string[] args)
{
DoTaskWithAsync();//启动任务
Console.ReadLine();
}
//启动多线程
public static async void DoTaskWithAsync()
{
Console.WriteLine("启动多线程任务");
await Task.Run(()=> {
DoTaskFunction();
});
}
//执行的任务
public static void DoTaskFunction()
{
for (int i = 0; i <= 5; i++) {
Console.WriteLine("任务 {0} 完成!",i);
}
}
}
}