gpt4 book ai didi

c# - 是什么阻止了我的异步函数设置中的主线程?

转载 作者:行者123 更新时间:2023-11-30 16:37:24 25 4
gpt4 key购买 nike

我刚开始使用异步函数并遇到了主线程 block 。我的代码的哪一部分导致了这个?任何帮助将不胜感激

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

我原以为它会在非主线程上异步运行,但无论如何它都会阻塞主线程。

最佳答案

您所看到的并不是严格意义上的“阻塞”本身,而是 async 代码的延续(即 async 方法的“剩余”部分) await 已完成)执行 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.

如果您将 .ConfigureAwait(false) 附加到您等待的调用,您应该避免这种行为 - 但请注意,这可能会干扰您在延续中使用 Unity API 的能力。

关于c# - 是什么阻止了我的异步函数设置中的主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com