I just got started with async functions and am running into mainthread block. What part of my code causes this? Any help would be appreciated
//mainthread function
private void ShortestPathBetweenNodes(Node start , Node)
{
RunDijkstraAsync(start, target);
}
async void RunDijkstraAsync(Node start, Node target)
{
List<Node> path = new List<Node>();
path = await DijkstrAsync(start, target);
}
async Task<List<Node>> DijkstrAsync(Node start, Node target)
{
await Task.Run(() =>
{
//omitted function code. markedNode.previous is the List<Node> to return
return markedNode.previous;
});
}
I expected this to run async on a non-mainthread, but it blocks the mainthread regardless.
What you're seeing isn't strictly "blocking" per se but rather the continuations of your async code (i.e. the "remainder" of the async method after the await has completed) executing on the main thread due to Unity's custom synchronization context:
Unity does provide one important piece for us however. As you can see in the above example, our async methods will be run on the main unity thread by default. [...] it works this way because Unity has provided a default SynchronizationContext called UnitySynchronizationContext which automatically collects any async code that is queued each frame and continues running them on the main unity thread.
If you append .ConfigureAwait(false) to your awaited calls you should get around this behaviour - but note that this will likely interfere with your ability to use Unity APIs in your continuations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With