Archive

Threading

Controls can be accessed and manipulated only from those thread in which it is created. If we are in some other thread and want to access the controls of another thread we need to follow on different way. Directly accessing will generate the exception saying control were created in another thread so can’t be accessed.

To sort our this first we have to check the function “IsInvokeRequired” of the control. if it is true then it is in another thread and we need to call it with the help of “Invoke” or “BeginInvoke” methods.

private void Form1_Load(object sender, EventArgs e)
{
NewThread();
}

public void NewThread()
{
Thread thread = new Thread(new ThreadStart(threadMethod));
thread.Start();
}

public void threadMethod()
{
if (this.InvokeRequired)
{ 
this.Invoke(new MethodInvoker(threadMethod));
}
else            
{
this.Text = "Form caption is changed";
}
}
Follow

Get every new post delivered to your Inbox.