[ACCEPTED]-WPF asynchronous Task<T> blocking UI-task
Accepted answer
Your main thread is blocking because the 6 call to Task.Result
waits until the Task
has completed. Instead 5 you can use Task.ContinueWith()
to access the Task.Result
after the Task
has completed. The 4 call to TaskScheduler.FromCurrentSynchronizationContext()
causes the continuation to run 3 on the main UI thread (so you can access 2 _button
safely).
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_button.IsEnabled = false;
Task<Boolean>.Factory.StartNew(() =>
{
Thread.Sleep(5*1000);
return true;
}).ContinueWith(t=>
{
if (t.Result)
_button.IsEnabled = true;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
Update
If you are using C# 5 you can use 1 async/await instead.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_button.IsEnabled = false;
var result = await Task.Run(() =>
{
Thread.Sleep(5*1000);
return true;
});
_button.IsEnabled = result;
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.