using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace example1 { public partial class frmoperations : Form { private int increment; private int square; private int loopvalue; private System.Threading.Thread objsquare; private System.Threading.Thread objincrement; private System.Threading.Thread objloop; public frmoperations() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btnsquare_Click(object sender, EventArgs e) { square = int.Parse(txtnum.Text); btnsquare.Enabled = false; ChooseThreads(1); } private void btnincrement_Click(object sender, EventArgs e) { increment = int.Parse(txtnum.Text); btnincrement.Enabled = false; ChooseThreads(2); } private void btnloop_Click(object sender, EventArgs e) { loopvalue = int.Parse(txtnum.Text); btnloop.Enabled = false; ChooseThreads(3); } public void ChooseThreads(int threadnumber) { switch (threadnumber) { case 1: objsquare = new System.Threading.Thread(new System.Threading.ThreadStart(this.runsquare)); objsquare.Start(); break; case 2: objincrement = new System.Threading.Thread(new System.Threading.ThreadStart(this.runincrement)); objincrement.Start(); break; case 3: objloop = new System.Threading.Thread(new System.Threading.ThreadStart(this.runloop)); objloop.Start(); break; } } public void runsquare() { double result; Console.WriteLine("running square thread"); result = square * square; lblsquare.Text = "the square is :" + result.ToString(); btnsquare.Enabled = true; } public void runincrement() { int result1 = increment + 9; Console.WriteLine("running the increment thread"); lblinc.Text = " the incremented value is" + result1.ToString(); btnincrement.Enabled = true; } public void runloop() { int index; Console.WriteLine("loop"); for(index=1;index<=loopvalue;index++) { Console.WriteLine ("running loop"); System .Threading .Thread .Sleep(500); } btnloop.Enabled = true; lblloop.Text = " executed the loop" + loopvalue.ToString()+"times";
} } }
|
Serban CosminPosted Jun 8, 2010, 8:41 AM
For every user interface element that you want to modify from a separate thread, you must use the Invoke method, otherwise you will get the error you mention. You must first create a delegate and a method that modifies the user interface, like this:
delegate void ModifyText( string msg );
private void ModifyLabelText( string msg )
{
lblinc.Text = msg;
}
// in the thread method :
ModifyText modifyText = new ModifyText( ModifyLabelText );
this.Invoke( modifyText, new object[ ] { "The incremented value is .... " } );
This should do the trick.
You can create something similar for modifying the button's state.