如何检测,如果我们是在UI线程? [英] How to detect if we're on a UI thread?

查看:170
本文介绍了如何检测,如果我们是在UI线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关参数的缘故,考虑UI线程作为不得不 Application.Run()或它的一个重载呼吁,并具有呼叫线程活动消息循环运行。

For the sake of argument, consider a UI thread as a thread that has had a call to Application.Run() or one of it's overloads called on it and has an active message loop running.

是否有检测,如果我们目前这样一个线程执行?

Is there a way of detecting if we're currently executing on such a thread?

我想这样做的原因是因为我有一个私人的功能即是长期运行的类。类本身已经是多线程的,而这个类的用法是这样的,它可能无论从UI还是从后台线程做处理中。这个功能也属于这一网络。但我不希望它堵塞UI线程。所以我想检测是否我的UI线程,如果是这样运行的,叉函数调用到后台线程(可能是线程池,但这是一个非的问题本讨论)。这完全是乖巧,但在后台线程可能依靠函数的输出,所以阻止对他们来说是更好的,而UI线程在一个更设置和忘记的方式对其进行访问。

The reason I want this is because I have a class with a private function that is long-running. The class itself is already multithreaded, and the usage of this class is such that it might be used from either the UI or from background threads doing processing. This function also falls into this net. But I don't want it to block up the UI thread. So I want to detect if I am running on a UI thread and if so, fork the function call into a background thread (probably ThreadPool, but that's a non-issue for this discussion). This is entirely well-behaved, but the background threads are probably relying on the output of the function, so blocking for them is better, whereas the UI thread is accessing it in a more "set-and-forget" manner.

推荐答案

我会建议它的那种决定方应做出的。你总是可以写的包装方法,使其更容易 - 但它意味着你不会有在一个奇的局面被调用者(如问题的UI框架,你不知道,还是其他什么东西与事件循环),你让他们错误的决定。

I would suggest that it's the kind of decision the caller should make. You could always write wrapper methods to make it easier - but it means that you won't have problems with the caller being in an "odd" situation (e.g. a UI framework you don't know about, or something else with an event loop) and you making the wrong decision for them.

如果该方法可能需要以提供正确的线程反馈,我想传递一个 ISynchronizeInvoke (由实施控制)做,在UI无关的方式。

If the method ever needs to provide feedback in the right thread, I'd pass in an ISynchronizeInvoke (implemented by Control) to do that in a UI-agnostic way.

这篇关于如何检测,如果我们是在UI线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆