在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
BackgroundWorker 可用于启动后台线程,避免出现界面假死状态
下面是一个简单的例子: 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 }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论