gpt4 book ai didi

c# - 是否有System.Threading.SynchronizationContext.Current.PostAsync()?

转载 作者:行者123 更新时间:2023-12-03 13:21:49 24 4
gpt4 key购买 nike

我可以像这样将任何东西返回到UI线程:

// when I am on the UI thread
var _UI = System.Threading.SynchronizationContext.Current;
// then on a background thread
_UI.Post((x) => { DoSomething(); }, null);

但是,如果我在该后台线程上使其与 异​​步在一起,则调用_UI.Post()将撤消我的工作,而 使UI等待来执行DoSomething()。

当然_UI.PostAsync()是伪代码。但是 是否可以在UI线程上执行,但是可以以异步方式执行?从根本上讲,我意识到我正在暴露自己对知识和理解的缺乏。请仁慈。我只是问问 ;)

最佳答案

SynchronizationContext.Post()不会阻塞后台线程,因为它异步地“发回” UI线程(在这种情况下)。

UI线程只会在DoSomething()调用的持续时间内阻塞-但是在这种情况下,您是说必须在UI线程上运行它,在这种情况下,它将阻塞UI线程。

这里的关键是将大部分工作放在后台线程上,并且仅调用.Post(...)进行直接设置用户界面的操作。因此,它们应该是非常快速的操作,并且绝不能(特别是)阻止UI。

关于c# - 是否有System.Threading.SynchronizationContext.Current.PostAsync()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7277189/

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