Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Winforms button while OnClick code executes in background

I have some code in my "button_click" action. I want to disable the button during this code working.

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        button1.IsEnabled = false;
        // some code (its take about 2-5 sec)
        button1.IsEnabled = true;
    }

But this doesn't work. The button never disables.

like image 434
Misha Avatar asked Feb 21 '26 23:02

Misha


2 Answers

You need to run the "some code" part on a background thread:

button1.Enabled = false;
Task.Factory.StartNew(() => {
    // some code (its take about 2-5 sec)
}).ContinueWith(task => {
    button1.Enabled = true;
}, TaskScheduler.FromCurrentSynchronizationContext());
like image 187
McGarnagle Avatar answered Feb 24 '26 13:02

McGarnagle


That is because your UI locks up during the entire action.

You should write the task in some sort of background thread.

You can use the BackgroundWorker for that, but better a Task.

BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;

button.Enabled = false;

bgw.RunWorkerAsync();

private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
   // your task
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // update the button
    button.Enabled = true;
}
like image 27
Patrick Hofman Avatar answered Feb 24 '26 12:02

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!