代码很简单:
public partial class TaskParallelTestForm01 : Form { public TaskParallelTestForm01() { InitializeComponent(); } string[] GenerateList() => new string[500]; void DoWork() { Thread.Sleep(50); } private void BtnRun_Click(object sender, EventArgs e) { var list = GenerateList(); progressBar1.Maximum = list.Length; Task.Run(() => Parallel.ForEach(list, item => { DoWork(); // Update the progress bar on the Synchronization Context that owns this Form. this.Invoke(new Action(() => this.progressBar1.Value++)); })); } }
效果图:
下一篇(高级篇):一个利用 Parallel.For 并行处理任务,带有进度条(ProgressBar)的 WinForm 实例(下)
谢谢浏览!