private void but_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
doSomeThing();//e.g run for more than 20 seconds
(sender as Button).IsEnabled = true;
}
When I press the button at first time it disables. Then starts doSomeThing() and it contains UI code or some UI variable updated.
I mean while if I press the button again while doSomeThing() is in progress then but_Click event fires again after this button enables back.
It maintains queue of event fired,i.e. n number of times which i pressed.
So, how to prevent firing event while button is disabled?
Please consider in this scenario ‘doSomething’ contains UI controls bind to code. So we can’t run background Thread in this case.
Help me with solution.
The issue with this code is
doSomeThing()method is running in UI Thread. So, the Button is not properly disabled. If we refactor the code so thatdoSomeThing()method runs in a different thread, it will just work fine. Here is a simple example usingBackgroundWorker; however the idea is we should not run time consuming stuffs in UI thread. Here is the refactored code:I did not follow any coding conversions here as I just wanted to share my idea. Please note that, I named the WPF button as “btn”.