BackgroundWorker 可用于启动后台线程,避免出现界面假死状态
注:界面假死状态:例如执行一个比较耗时的操作(CPU密集运算),在该操作执行完之前去操作界面,会出现界面停止响应的情况
下面是一个简单的例子:
1 static void Main(string[] args) 2 { 3 CreateFish(); 4 Console.ReadKey(); //这里要暂停一下,不然CreateFish()方法执行完程序就结束了,看不到效果 5 } 6 private static void CreateFish() 7 { 8 //using System.ComponentModel 9 BackgroundWorker worker = new BackgroundWorker(); 10 //DoWork:调用RunWorkerAsync()时发生,并且传递DoWorkEventArgs参数 11 worker.DoWork += delegate (object sender, DoWorkEventArgs e) 12 { 13 Fish fish = Nature<Fish>.Create(); 14 fish.Name = "Mermaid"; 15 fish.Age = 18; 16 e.Result = fish; 17 }; 18 //后台操作完成或中途终止会触发该事件 19 worker.RunWorkerCompleted += delegate (object sender, RunWorkerCompletedEventArgs e) 20 { 21 if (e.Error != null) 22 { 23 Console.WriteLine("发生异常,异常信息:" + e.Error.Message); 24 return; 25 } 26 Fish fish = e.Result as Fish; 27 Console.WriteLine($"自然生成一条鱼,名称:{fish.Name},年龄:{fish.Age}"); 28 }; 29 worker.RunWorkerAsync(); //开始执行后台操作 30 }