gpt4 book ai didi

c# - 为什么设置表单的 enabled 属性会使应用程序崩溃?

转载 作者:行者123 更新时间:2023-11-30 15:48:06 27 4
gpt4 key购买 nike

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 秒后,我的程序崩溃了。为什么?

最佳答案

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

您可以使用窗体或控件对象上的 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;
}
}

关于c# - 为什么设置表单的 enabled 属性会使应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com