|
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");
}
|