【问题标题】:Show and Close form from a background thread从后台线程显示和关闭表单
【发布时间】: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();
    } 

如何打开表单而不是按住它,以便稍后完成长任务时我可以取消将关闭窗口的任务 (警报表单)?

【问题讨论】:

    标签: c# task-parallel-library


    【解决方案1】:

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

    alert.Invoke((MethodInvoker)delegate () 
    {
        alert.Close();
    });
    

    【讨论】:

    • 它不是常规的 winforms,但是当这个窗口启动并运行时,我需要通过取消来关闭它?
    猜你喜欢
    • 2021-05-29
    • 2012-07-26
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2016-10-28
    • 2019-11-02
    相关资源
    最近更新 更多