C# 知识点集锦(二)异步入门,在其他线程更新UI,异常处理
一。多线程创建
Task.Factory.StartNew( delegate { TimeConsumingTask(); } ); Task.Factory.StartNew( () => { TimeConsumingTask(); } ); Task.Run( () => { TimeConsumingTask2(); }); ThreadPool.QueueUserWorkItem(o => { TimeConsumingTask2(); });
二。在其他线程中修改UI
方式一:
this.label1.Invoke((MethodInvoker)delegate { this.label1.Text = "Time is UP"; });
方式二:使用Dispatcher
先在UI线程中 dispatcher = Dispatcher.CurrentDispatcher; 在工作线程中 dispatcher.Invoke(() => { this.label1.Text = "Time is UP2"; });
方式三:使用async await 和Progress类
private async void button1_Click(object sender, EventArgs e) { var progress = new Progress<string>((o)=>this.label1.Text=o+"%"); await Task.Factory.StartNew(()=>LongWork(progress), TaskCreationOptions.LongRunning); } private void LongWork(IProgress<string> progress) { for (var i = 1; i <= 100; i++) { Task.Delay(100).Wait(); progress.Report(i.ToString()); } }
三 线程中异常的处理
情况1.以上面为例,将async函数的内容使用try包裹起来,异步方法中在合适的情况下抛出异常。
private async void button1_Click(object sender, EventArgs e) { button1.Enabled = false; try { var progress = new Progress<string>((o) => this.label1.Text = o + "%"); await Task.Factory.StartNew(() => LongWork(progress), TaskCreationOptions.LongRunning); } catch (Exception ex) { this.label1.Text="Failed : "+ex.Message; } button1.Enabled = true; } private void LongWork(IProgress<string> progress) { for (var i = 1; i <= 100; i++) { if (i >= 40) throw new Exception("Over 40 ,there is always an Exception。。"); Task.Delay(100).Wait(); progress.Report(i.ToString()); } }
处理异常例子2
private async void button1_Click(object sender, EventArgs e) { try { this.label1.Text = await JustDO(); } catch (Exception ex) { this.label1.Text=ex.Message; } } private Task<string> JustDO() { return Task.Run(() => { Task.Delay(TimeSpan.FromSeconds(4)).Wait(); throw new Exception("oooops"); return Task.FromResult("OK"); }); }