2011-01-05 65 views
1

我有一个使用C#开发的Windows应用程序。在这个应用程序中,我正在创建一个过程。 我想在Process_Exited()事件发生时启用和禁用几个按钮。 在Process_Exited()方法,我编写的代码,以使按钮,但在运行时,我得到错误的如何在进程退出后启用表单按钮?

“跨线程操作无效: 控制 ‘tabPage_buttonStartExtraction’ 从比其他线程访问 它创建的线程。“

我的代码片断是:

void rinxProcess_Exited(object sender, EventArgs e) 
{ 
    tabPage_buttonStartExtraction.Enabled = true; 
    tabPageExtraction_StopExtractionBtn.Enabled = false; 
} 

任何人都可以建议如何实现这一目标?

回答

2

您正在尝试的UI从不同的线程改变。 尝试这样的事情;

private void SetText(string text) 
    { 
     // InvokeRequired required compares the thread ID of the 
     // calling thread to the thread ID of the creating thread. 
     // If these threads are different, it returns true. 
     if (this.textBox1.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(SetText); 
      this.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      this.textBox1.Text = text; 
     } 
    } 

你不应该在另一个线程上在UI上做很多工作,因为调用非常昂贵。

来源:http://msdn.microsoft.com/en-us/library/ms171728.aspx

3

在单独的方法中移动启用/禁用行,并使用Control.Invoke方法从rinxProcess_Exited调用该方法。

2

您必须在UI线程上进行UI更改。有关更多详细信息,请参阅this question

这里的应用到您的示例解决方案:

void rinxProcess_Exited(object sender, EventArgs e) 
{ 
    if (this.InvokeRequired) 
    { 
     this.Invoke((Action)(() => ProcessExited())); 
     return; 
    } 

    ProcessExited(); 
} 

private void ProcessExited() 
{ 
    tabPage_buttonStartExtraction.Enabled = true; 
    tabPageExtraction_StopExtractionBtn.Enabled = false; 
} 
+0

它可以在.net 2.0框架上工作吗?我认为=>运算符被添加到3.5框架中 – Shekhar 2011-01-05 06:41:06

+0

你是对的。如果您使用2.0框架,则必须使用委托而不是匿名方法。我只是假设3.5或更高。 – 2011-01-05 17:23:49