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.
1 2 3 4 5 6 | private void UpdateStatus(string statusText) { // Body of the function } |
First of all you need to create a delegate with matching signature of this function
1 2 3 | delegate void UpdateStatusInvoker(string statusText) |
Now to call this function from a separate thread use Invoke method with parameters
1 2 3 | 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.
1 2 3 4 5 6 7 8 9 10 | if (this.InvokeRequired) { this.Invoke(new UpdateStatusInvoker(UpdateStatus), "Status text"); } else { UpdateStatus("Status text"); } |