How to detect if we're on a UI thread?

∥☆過路亽.° 提交于 2019-12-01 02:44:57

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.

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.

If you have access to a Form or a Control, you can check the InvokeRequired property; this will return false if you are on the UI thread and true if you are not.. If it happens in a context where you cannot check against a Control, you could easily set up a static property in your program that you could check against. Store a reference to Thread.CurrentThread at startup, and compare Thread.CurrentThread to that reference when you need to know:

static class Program
{
    private static Thread _startupThread = null;

    [STAThread]
    static void Main()
    {
        _startupThread = Thread.CurrentThread;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public static bool IsRunningOnStartupThread()
    {
        return Thread.CurrentThread == _startupThread;
    }
}

By calling Program.IsRunningOnStartupThread you will get a bool saying if you are or not.

bool isMessageLoopThread = System.Windows.Forms.Application.MessageLoop;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!