DeadLock on task.Wait() with Task which edit UI

后端 未结 1 1424
死守一世寂寞
死守一世寂寞 2021-01-27 11:41

I\'m trying to find some solutions to my problem here, but with no result (or I just do not get them right) so if anyone could help / explain i will be really gratefull.

相关标签:
1条回答
  • 2021-01-27 11:47

    You have a deadlock because ping.Wait(); blocks UI thread.

    You should wait for task asynchronously using await.

    So, if Stop() is event handler then change it to:

    public async void Stop() // async added here
    {
        if (running)
        {
            tokenSource.Cancel();
            await ping; // await here
            ping.Dispose();
            tokenSource.Dispose();
        }
    
        running = false;
    }
    

    If it is not:

    public async Task Stop() // async added here, void changed to Task
    {
        if (running)
        {
            tokenSource.Cancel();
            await ping; // await here
            ping.Dispose();
            tokenSource.Dispose();
        }
    
        running = false;
    }
    

    As mentioned by @JohnB async methods should have Async suffix so, the method should be named as StopAsync().

    Similar problem and solution are explained here - Do Not Block On Async Code

    You should avoid synchronous waiting on tasks, so you should always use await with tasks instead of Wait() or Result. Also, as pointed by @Fildor you should use async-await all the way to avoid such situations.

    0 讨论(0)
提交回复
热议问题