WPF asynchronous Task<T> blocking UI WPF asynchronous Task<T> blocking UI wpf wpf

WPF asynchronous Task<T> blocking UI


Your main thread is blocking because the call to Task.Result waits until the Task has completed. Instead you can use Task.ContinueWith() to access the Task.Result after the Task has completed. The call to TaskScheduler.FromCurrentSynchronizationContext() causes the continuation to run on the main UI thread (so you can access _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 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;      }