我有这个功能:
public void NudgeMe()
{
int xCoord = this.Left;
int yCoord = this.Top;
int rnd = 0;
Random RandomClass = new Random();
for (int i = 0; i <= 500; i++)
{
rnd = RandomClass.Next(xCoord + 1, xCoord + 15);
this.Left = rnd;
rnd = RandomClass.Next(yCoord + 1, yCoord + 15);
this.Top = rnd;
}
this.Left = xCoord;
this.Top = yCoord;
}
我在这里调用这个函数:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
{
soundPlay = true;
blinking_label();
NudgeMe();
}
else
{
soundPlay = false;
stop_alarm = true;
}
cpuView();
gpuView();
Thread.Sleep(1000);
}
}
}
我得到的异常是: invalidOperationException 跨线程操作无效:控件'Form1'从创建它的线程以外的线程访问
例外是在 NudgeMe() 中的行:
this.Left = rnd;
这条线被涂成绿色。
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'Form1' 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.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Form.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Control.SetBounds(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Control.set_Left(Int32 value)
at HardwareMonitoring.Form1.NudgeMe() in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 782
at HardwareMonitoring.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 727
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException: