這是我在Form2上設置某些組件狀態的一個小方法。當我從Form2調用它時加載它。工作正常,但是當我把它從Form1中(需要更新一些州),我得到一個異常:當我從Form1調用我的方法時C#交叉線程操作異常
「System.InvalidOperationException」類型的未處理的異常出現在System.Windows.Forms.dll中
附加信息:跨線程操作無效:從其創建線程以外的線程訪問的控件'button1'。
public void SetleMotor1()
{
button1.Enabled = true;
button2.Enabled = false;
if (Form1.Motor1.Calibstate == 3)
label4.Text = "Befejezve";
else
label5.Text = "Megállt";
if (Form1.Motor1.Calibrated)
{
label21.Text = "Igen";
label6.Text = Convert.ToString(Form1.Motor1.MMImp);
}
else
{
label21.Text = "Nem";
label6.Text = "-";
}
}
請問我在這裏錯過了什麼?
下面是從Form1的代碼調用該方法在Form2:
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// reading the data etc etc etc...then evaluating:
case 1:
if ((data[1] == 40) && (Motor1.Calibstate == 3))
{
long impulses = (65536 * data[2] + 256 * data[3] + data[4]);
Form2.SetleMotor1(); // <----- this is where it happens
Motor1.Calibstate = 0;
zaloguj("A Motor 1 kalibrációja befejezve");
if (Motor1.Debug)
zaloguj("A Motor 1 köre " + Convert.ToString(impulses) + " impulzus");
Motor1.MMImp = Convert.ToInt32(impulses/360);
Motor1.Calibrated = true;
if (Motor1.Debug)
zaloguj("M1Imp/deg: " + Convert.ToString(Motor1.MMImp));
}
break;
// other similar code ...
}
您可以在此處將代碼放在您要調用該方法的位置。 – terrybozzio
[Cross-thread operation not valid:可以從一個線程以外的線程訪問它的線程](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control -accessor-from-a-thread-other-the- –
另外請告訴我們,如果你在設計器或代碼中創建'button'?如果在代碼中,也請告訴我們。 –