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.
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.