繁体   English   中英

如何从另一个线程关闭Form.ShowDialog,然后显示第二个Form。

[英]How to close Form.ShowDialog from another thread and then display second Form.

我想要实现的是在长时间运行中显示 FirstForm。 该操作结束后,我想关闭 FirstForm并显示 SecondForm。 下面是示例代码:对于我的惊奇,Close无法正常工作(两种形式均可见)。

using System;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FormMain());
    }
}

class FormMain : Form
{
    public FormMain()
    {
        var button = new Button() { Text = "test" };
        button.Click += (o, e) =>
        {
            var first = new FormFirst();
            Task.Factory.StartNew(() =>
            {
                ////some long operation...
            }).ContinueWith(t => {
                first.Close();
                var second = new FormSecond();
                second.ShowDialog();
            }, TaskScheduler.FromCurrentSynchronizationContext());
            first.ShowDialog();
        };

        Controls.Add(button);
    }
}

class FormFirst : Form
{
    public FormFirst() { Text = "First"; }
}

class FormSecond : Form
{
    public FormSecond() { Text = "Second"; }
}
}

我使用Form.Invoke解决了这个问题,但这是正确的方法吗?:

var first = new FormFirst();
Task.Factory.StartNew(() =>
{
   ////some long operation...
   var created = new AutoResetEvent(first.IsHandleCreated);
   first.HandleCreated += (o1,e1) => created.Set();
   created.WaitOne();
   first.Invoke(new Action(() => first.Close()));
}).ContinueWith(t =>
{
    first.Close();
    var second = new FormSecond();
    ...

使用invoke是正确的方法。

由于WinForms控件不是线程安全的, 因此添加了属性,以确保可以访问表单方法的唯一线程是创建该方法的线程。 如果该属性设置为true,则直接从另一个线程调用表单的方法不起作用。 现在,您可以将其设置为false并继续您的生活,但是请注意,这是有充分原因的。

使用Form.Invoke是正确的,线程安全的方法来完成您要实现的目标。 如果需要进一步的说明,可以参考 MSDN页面,以创建对WinForms控件的线程安全调用。 另外,如果您有兴趣找出为什么会这样,用户Adriano Repetti会在这个答案中很好地解释它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM