在 Form1 顶部我添加了这个:
bool completed;
AutoResetEvent autoreset;
在构造函数中我做了:
completed = false;
autoreset = new AutoResetEvent(false);
在后台工作人员 DoWork 事件中,我做了:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
completed = true;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
{
soundPlay = true;
NudgeMe();
}
else
{
soundPlay = false;
stop_alarm = true;
}
tempCpuValue = Core.cpuView(pauseContinueDoWork,cpu,this,data,tempCpuValue,button1);
tempGpuValue = Core.gpuView(pauseContinueDoWork,data,tempGpuValue,button1);
this.Invoke(new Action(() => data = new List<string>()));
tempCpuValue = Core.cpuView(pauseContinueDoWork, cpu, this, data, tempCpuValue, button1);
tempGpuValue = Core.gpuView(pauseContinueDoWork, data, tempGpuValue, button1);
this.Invoke(new Action(() => listBox1.DataSource = null));
this.Invoke(new Action(() => listBox1.DataSource = data));
//listBox1.DataSource = data;
}
}
autoreset.Set();
}
然后在 Form1 结束事件中我做了:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
if (completed == true)
{
this.backgroundWorker1.CancelAsync();
autoreset.WaitOne();
}
}
}
当它在执行 WaitOne() 时,表单刚刚回到中间显示并且程序正在冻结我所能做的就是在视觉工作室调试>停止调试
我想这样做是为了避免异常,我有时会在 RaceOnRCWCleanup 上获得一些关于多线程的信息。
有时在关闭程序时,我上了另一个课,这个异常:
System.ObjectDisposedException was unhandled by user code
HResult=-2146232798
Message=Cannot access a disposed object.
Object name: 'Form1'.
Source=System.Windows.Forms
ObjectName=Form1
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at HardwareMonitoring.Core.cpuView(Boolean pause, CpuTemperature cpuTemp, Form1 f1, List`1 myData, Nullable`1 myCpuTemp, Button b1) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Core.cs:line 55
at HardwareMonitoring.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 427
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
就像在 backgroundworker 完成工作之前处理的 form1 和 backgrounddworker dowork 事件正在使用此类方法一样。