私はこの機能を持っています:
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: