1.使用 async await
2.返回值
static void Main(string[] args) { Program p = new Program(); Console.WriteLine(1); p.Go(); Console.WriteLine(2); Console.ReadLine(); } async Task Go() { Console.WriteLine(3); await a(); Console.WriteLine(4); } async Task a() { Console.WriteLine(5); int i = await b(); Console.WriteLine(i); } async Task<int> b() { Console.WriteLine(6); await Task.Delay(5000); Console.WriteLine(7); int i = 999; return i; }
2以后暂停几秒后继续执行
3.异步lambda表达式
4.异步更新UI
Random random = new Random(); private void button1_Click(object sender, EventArgs e) { Test(); } public async void Test() { while (1 == 1) { string temp = await TestAsync(); textBox1.Text = temp.ToString(); } } Task<string> TestAsync() { return Task.Run(() => { Thread.Sleep(1000); return random.Next(1, 100).ToString(); }); }
5.主线程异步 4.5新增
static async Task Main(string[] args) { HttpClient httpClient = new HttpClient(); var msg = await httpClient.GetAsync("https://www.baidu.com/"); Console.WriteLine(msg.StatusCode); Console.ReadKey(); }