[ACCEPTED]-WPF asynchronous Task<T> blocking UI-task

Accepted answer
Score: 10

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;      
}

More Related questions