gpt4 book ai didi

c# - WPF 应用程序中的后台线程和 UI 线程

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:37 24 4
gpt4 key购买 nike

我正在阅读 DataModel-View-ViewModel pattern: 2

我真的不明白需要检查我是在 UI 线程还是后台线程中。如果我跳过检查怎么办。另外,下面的代码......

[Conditional("Debug")]
protected void VerifyCalledOnUIThread()
{
Debug.Assert(Dispatcher.CurrentDispatcher == this.Dispatcher,
"Call must be made on UI thread.");
}

并没有真正做任何事情,例如。设定值。那么,如果我不调试,它会做任何事情吗?

最佳答案

I don't really understand the need to check if I am in the UI or Background thread. what if i skip the checks.

使用 Dispatcher 并检查您是在 UI 还是后台线程上的原因是因为 WPF 要求控件只能在创建它们的线程上访问。这是因为控件不是线程安全的。如果您没有进行多线程处理(即您的所有代码都在主线程上),那么您不必担心这一点。 WinForms 也有同样的限制。

如果您尝试从与创建它的线程不同的线程访问控件,您将得到一个 InvalidOperationException

Also, the code below...does not really do anything, eg. set values. So if I am not debugging will it do anything at all?

编译发布版本时,Debug.Assert(和您的VerifyCalledOnUIThread 方法)甚至不会出现在代码中,所以不会,什么也不会发生。

关于c# - WPF 应用程序中的后台线程和 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765429/

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