Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms execute code in separate thread

a bit of a juvenile question...

I realise that in a Winforms app, long running code should be executed in its own thread. How does one accomplish this on say, a button click event?

I want to do this in an effort to free up the UI thread so that I can simultaneously overlay the current form with a semi-transparent modal dialog form. I've aleady created the modal dialog form with a neat loading GIF located in the centre that works perfectly on a button click event on its own.

The reason I've chosen this method, is because (1) I want to block any user interaction with the form while the code is being executed, and (2) provide the user with an indication that processing is underway (I dont know how to judge how long a particular piece of code will take to execute, hence opting for an indefinite loading indicator gif).

Also, on the topic of executing code in separate threads...should this not apply to any code, or only specifically to long-running code?

I would really appreciate any help on this matter! thank you!

like image 798
Shalan Avatar asked Dec 07 '22 06:12

Shalan


1 Answers

One of the simplest ways is to use a BackgroundWorker component. Add a BackgroundWorker to your form, add an event handler for the DoWork event, and call the long-running function from there. You can start it in your button click event handler by calling the RunWorkerAsync method on the BackgroundWorker component.

In order to know when the operation is ready, set up a handler for the RunWorkerCompleted event.

private void Button_Click(object sender, EventArgs e)
{
    myBackgroundWorker.RunWorkerAsync();
}

private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // long-running operation here; will execute on separate thread
}

private void myBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // operation is ready
}
like image 122
Fredrik Mörk Avatar answered Jan 03 '23 08:01

Fredrik Mörk