目标:MyForm上有个Button,按下后会执行Task,Task会返回中间结果,然后在Label上实时显示中间结果。
using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; public partial class MyForm : Form { //1)Label的更新 private readonly object statusLabel = new object(); private void UpdateLabel(string txt) { lock (statusLabel) { this.Label1.Text = txt; } } //2)Task定义 Random rand = new Random(); public void SearchFilesInTarget(IProgress<string> onSearchingFile) { while (true) { string result = "file_name" + rand.Next(); onSearchingFile.Report(result); } } //3)按钮按下 private readonly CancellationTokenSource cancelToken = new CancellationTokenSource(); private void SearchStart_Click(object sender, EventArgs e) { var onSearchingFile = new Progress<string>(txt => this.BeginInvoke(updateLabel, "Searching..." + txt)); Task myTask = Task.Factory.StartNew(() => SearchFilesInTarget(onSearchingFile), cancelToken.Token); } //4)构造BeginInvoke的参数 public delegate void DelegateUpdateLabel(string file); private DelegateUpdateLabel updateLabel; public MyForm() { updateLabel = new DelegateUpdateLabel(UpdateLabel); } }