【发布时间】:2018-08-03 04:38:18
【问题描述】:
我有一个显示进度条的 Windows 窗体 (AlertForm)。我试图通过一项任务向它展示关闭它。我遇到的问题是,当我生成一个线程并调用 winforms.showdialog() 时,它持有该线程,因此无法取消它。我这样做是因为我正在通过 c# 编写一个 excel 添加,其中我没有面板来显示进度条。
static void Main(string[] args)
{
AlertForm alert = new AlertForm();
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
//while (true)
//{
// do some heavy work here
alert.ShowDialog();
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
alert.Close();
// another thread decided to cancel
Console.WriteLine("task canceled");
//break;
}
//}
}, ct);
// Simulate waiting 3s for the task to complete
Thread.Sleep(3000);
// Can't wait anymore => cancel this task
ts.Cancel();
Console.ReadLine();
}
如何打开表单而不是按住它,以便稍后完成长任务时我可以取消将关闭窗口的任务 (警报表单)?
【问题讨论】: