为什么设置表单的启用属性会导致应用程序崩溃?

3
private void launchbutton_Click(object sender, EventArgs e)
    {
        launchbutton.Enabled = false;
        Process proc = new Process();
        proc.EnableRaisingEvents = true;
        proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //The arguments/filename is set here, just removed for privacy.
        proc.Exited += new EventHandler(procExit);
        proc.Start();
    }

    private void procExit(object sender, EventArgs e)
    {
        MessageBox.Show("YAY","WOOT");
        Thread.Sleep(2000);
        launchbutton.Enabled = true;
    }

我退出创建的进程后,程序在2秒后崩溃了。为什么会这样?
1个回答

4

您正在不同于创建该控件(主UI线程)的线程上修改winform控件。 Winform控件不是线程安全的,如果您从创建它的任何线程以外的线程修改它们的状态,通常会抛出异常。

您可以使用Form或控件对象上找到的InvokeRequired属性和BeginInvoke方法来实现这一点。

例如,像这样:

    private void procExit(object sender, EventArgs e)
    {
        MessageBox.Show("YAY", "WOOT");
        Thread.Sleep(2000);
        // ProcessStatus is just a class I made up to demonstrate passing data back to the UI
        processComplete(new ProcessStatus { Success = true });
    }

    private void processComplete(ProcessStatus status)
    {
        if (this.InvokeRequired)
        {
            // We are in the wrong thread!  We need to use BeginInvoke in order to execute on the correct thread.
            // create a delegate pointing back to this same function, passing in the same data
            this.BeginInvoke(new Action<ProcessStatus>(this.processComplete), status);
        }
        else
        {
            // check status info
            if (status.Success)
            {
                // handle success, if applicable
            }
            else
            {
                // handle failure, if applicable
            }

            // this line of code is now safe to execute, because the BeginInvoke method ensured that the correct thread was used to execute this code.
            launchbutton.Enabled = true;
        }
    }

1
你给我的这两个属性/方法的定义让我感到头疼。你能提供一些我可以理解的代码吗?我通过例子学习。谢谢! - Steffan Donal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接