如何在后台工作DoWork事件中启用/禁用按钮?

时间:2013-08-02 09:43:39

标签: c# winforms

我有这个方法:

private void CreateDriversList()
        {
            try
            {
                StreamWriter w = new StreamWriter(contentDirectory + "\\" + "Drivers.txt");
                w.WriteLine("Module Name            Display Name           " + "             " + "                                        Driver Type");
                w.WriteLine("===========            ============ " + "             " + "                                                  ===========");
                System.Management.SelectQuery query = new System.Management.SelectQuery("Win32_SystemDriver");
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
                foreach (System.Management.ManagementObject ManageObject in searcher.Get())
                {
                    w.WriteLine("{0,-22} {1,-75} {2}", ManageObject["Namedfgfdg"], ManageObject["DisplayName"], ManageObject["ServiceType"]);
                    driversListNumbers += 1;
                }
                w.Close();
                Logger.Write("***** Drivers Text File Have Been Created *****");
            }
            catch(Exception err)
            {
                Logger.Write("There was an exception" + Environment.NewLine + err);
                SendEmail.Enabled = true;
            }

        }

这个方法是从DoWork事件中调用的,当我运行程序时我得到异常:

跨线程操作无效:控制从其创建的线程以外的线程访问的“SendEmail”

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=Cross-thread operation not valid: Control 'SendEmail' accessed from a thread other than the thread it was created on.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.get_Handle()
       at System.Windows.Forms.Control.OnEnabledChanged(EventArgs e)
       at System.Windows.Forms.ButtonBase.OnEnabledChanged(EventArgs e)
       at System.Windows.Forms.Control.set_Enabled(Boolean value)
       at Diagnostic_Tool_Blue_Screen.Form1.CreateDriversList() in d:\C-Sharp\Diagnostic Tool Blue Screen\Diagnostic Tool Blue Screen\Diagnostic Tool Blue Screen\Form1.cs:line 135
       at Diagnostic_Tool_Blue_Screen.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in d:\C-Sharp\Diagnostic Tool Blue Screen\Diagnostic Tool Blue Screen\Diagnostic Tool Blue Screen\Form1.cs:line 177
       at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
       at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
  InnerException: 

3 个答案:

答案 0 :(得分:3)

工作线程永远不应该触摸UI。请改用BeginInvoke

SendEmail.BeginInvoke((Action)delegate() { SendEmail.Enabled = true; });

答案 1 :(得分:2)

您的选择

callig和处理WorkerProcess的OnRunWorkerCompleted事件 - http://msdn.microsoft.com/en-us/library/System.ComponentModel.BackgroundWorker_methods.aspx

或使用检查是否需要调用,然后在控件上使用Invoke - http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx

答案 2 :(得分:0)

你不能这样做。控件驻留在UI线程上,并且您尝试从另一个线程修改控件,这是不可能的。您必须将结果返回到UI线程,并从那里对控件执行适当的操作。