void Test1() { ChangeText("=========================================================="); ChangeText("i am washing left now ..."); } // 执行Test 方法为 Test线程 async void Test() { await playGameAsync(); // Main 线程遇到 await, 会拆分出 Test线程. 此时, Main线程回调到Main方法,Test线程继续执行 playGameAsync()方法 ChangeText("=========================================================="); ChangeText("i am washing right now ..."); } // 执行 playGameAsync 为 play线程 async Task playGameAsync() { await Task.Run(() => { // Test 线程来这也会拆分两个线程(但是play线程回调时因为自己被await修饰了, 所以不能像Main线程一样立即向下执行),需要等待 play线程执行完成 Task.Delay(3000).Wait(); ChangeText("I am play game .."); }); Task.Delay(3000).Wait(); ChangeText("i am finish play game"); } void ChangeText(string txt) { // 安全地更新Label的文本 if (textBox1.InvokeRequired) { textBox1.Invoke(new Action(() => { textBox1.Text += txt + "\r\n"; })); } else { textBox1.Text += txt + "\r\n"; } } private void button1_Click(object sender, EventArgs e) { Test(); // Main线程进入其中 Test1(); ChangeText("This is Main Finish ....."); }
标签:异步,play,am,学习,例子,线程,Test,Main,ChangeText From: https://www.cnblogs.com/jiaoyi1e/p/18547578