按钮线程安全调用Windows窗体控件C#

时间:2021-06-05 00:06:13

I had read this topic about how to Make Thread-Safe Calls to Windows Forms Controls .. But I don't really understand how to apply it to a button. In my case I have:

我已经阅读了关于如何对Windows窗体控件进行线程安全调用的这个主题..但我真的不明白如何将它应用于按钮。就我而言,我有:

button.Enabled = false;
new Thread(() =>
{                   
    doSomeWork();
    button.Enabled = true;           
}).Start();

I want to enable the button when Thread ends.

我想在线程结束时启用按钮。

1 个解决方案

#1


You need to use Invoke method in order to execute the code in UI thread:

您需要使用Invoke方法才能在UI线程中执行代码:

button.Enabled = false;
new Thread(() =>
{                   
   doSomeWork();
   this.Invoke((MethodInvoker) delegate {
         button.Enabled = true;
   });
}).Start();

#1


You need to use Invoke method in order to execute the code in UI thread:

您需要使用Invoke方法才能在UI线程中执行代码:

button.Enabled = false;
new Thread(() =>
{                   
   doSomeWork();
   this.Invoke((MethodInvoker) delegate {
         button.Enabled = true;
   });
}).Start();