C# 从后台线程显示并关闭窗体
我有一个显示进度条的windows窗体AlertForm。我试图通过一项任务来展示它。我遇到的问题是,当我生成一个线程并调用winforms.showdialog时,它会保留该线程,因此无法取消它。我这样做是因为我正在通过c编写excel加载项,其中没有显示进度条的面板C# 从后台线程显示并关闭窗体,c#,task-parallel-library,C#,Task Parallel Library,我有一个显示进度条的windows窗体AlertForm。我试图通过一项任务来展示它。我遇到的问题是,当我生成一个线程并调用winforms.showdialog时,它会保留该线程,因此无法取消它。我这样做是因为我正在通过c编写excel加载项,其中没有显示进度条的面板 static void Main(string[] args) { AlertForm alert = new AlertForm(); var ts = new Cancellat
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();
}
我如何打开表单而不持有它,以便在以后的阶段,当一个长任务完成时,我可以取消将关闭窗口的任务
AlertForm?如果AlertForm类是从Windows.Forms.Control继承的,则可以使用Invoke方法 alert.InvokeMethodInvokerdelegate { 警惕,关闭; };
它不是一个普通的winforms,但是当这个窗口最终启动并运行时,我需要关闭它,一旦它被取消?