Search 
DailyCoding > Windows

Using Invoke to access object in a windows forms/controls thread

How to use Invoke to handle cross thread calls to windows forms or controls
Author admin on May 26, 2008 0 Comments
Rate it    (Rated 3 by 1 people)
1,470 Views

Using asynchronous programming might be helpful in making the user's experience better. Asynchronous programming basically includes processing of a heavy operation into a separate thread to avoid the UI freezing and letting the user to perform other operations parallely. In a windows application whenever you try to access a windows forms or controls object from a different thread then you won't be able to do. To handle such kind to scenario, you can use Invoke to access a cross thread object

Suppose you have a function in you form which you want call from a separate thread.

private void UpdateStatus(string statusText)
{
  // Body of the function
}

First of all you need to create a delegate with matching signature of this function

delegate void UpdateStatusInvoker(string statusText)

Now to call this function from a separate thread use Invoke method with parameters

this.Invoke(new UpdateStatusInvoker(UpdateStatus), "Status text");

If you are not sure whether it will be called from a different thread, you can check whether invoke is required.

if (this.InvokeRequired)
{
  this.Invoke(new UpdateStatusInvoker(UpdateStatus), "Status text");
}
else
{
  UpdateStatus("Status text");
}
C# | Windows

Discussion

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved