我有这个方法:
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: