WPF asynchronous Task<T> blocking UI

青春壹個敷衍的年華 提交于 2019-12-05 10:50:31

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;      
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!