从后台线程显示和关闭表单

时间:2018-08-02 20:17:15

标签: c# task-parallel-library

我有一个显示进度条的Windows窗体(AlertForm)。我正在尝试通过一项任务来证明它的成功。我遇到的问题是当我生成线程并调用winforms.showdialog()时,它持有线程,因此无法取消它。我这样做是因为我正在通过C#编写一个excel add,其中没有面板显示进度条。

   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)?

1 个答案:

答案 0 :(得分:-2)

如果AlertForm类是从Windows.Forms.Control继承的,则可以使用Invoke方法

alert.Invoke((MethodInvoker)delegate () 
{
    alert.Close();
});
相关问题