异步学习小例子
1、异步
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 ....."); }
2、异步停止全部没有结束的
private async Task PerformAsyncOperation(CancellationToken cancellationToken,string str) { // 模拟长时间运行的操作 for (int i = 0; i < 10000; i++) { cancellationToken.ThrowIfCancellationRequested(); textBox1.Text += str + i + "\r\n"; if (str == "A") { await Task.Delay(1000); // 实际应用中这里会有长时间运行的代码 } else { await Task.Delay(100); // 实际应用中这里会有长时间运行的代码 } } } private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); private void button1_Click(object sender, EventArgs e) { cancellationTokenSource = new CancellationTokenSource(); // 启动异步操作 Task asyncTask = PerformAsyncOperation(cancellationTokenSource.Token, "A"); Task asyncTask1 = PerformAsyncOperation(cancellationTokenSource.Token, "B"); } private void button2_Click(object sender, EventArgs e) { // 取消异步操作 cancellationTokenSource.Cancel(); }
3、ThreadPool异步
private void button1_Click(object sender, EventArgs e) { // 启动异步操作 ThreadPool.QueueUserWorkItem(AsyncOperation, "A"); ThreadPool.QueueUserWorkItem(AsyncOperation, "B"); ThreadPool.QueueUserWorkItem(AsyncOperation, "C"); } private void AsyncOperation(object state) { for (var i = 0; i < 1000;i++){ // 使用InvokeRequired检查是否需要跨线程操作 if (textBox1.InvokeRequired) { // 跨线程调用更新UI textBox1.Invoke(new Action(() => { textBox1.Text += "异步操作完成 " + state + i + " \r\n"; })); } else { textBox1.Text += "异步操作完成 " + state + i + "\r\n"; } if (state == "A") { // 异步操作的代码,例如长时间运行的任务 Thread.Sleep(500); // 模拟耗时操作 } else { // 异步操作的代码,例如长时间运行的任务 Thread.Sleep(100); // 模拟耗时操作 } } }