如何在 C# 中启动 UI 线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/745057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:32:00  来源:igfitidea点击:

How to start a UI thread in C#

c#.netmultithreadinguser-interface

提问by Filip Fr?cz

I know I can start a new worker thread from with .NET. But how do I start a new UI thread (like in MFC)?

我知道我可以从 .NET 开始一个新的工作线程。但是我如何开始一个新的 UI 线程(就像在 MFC 中一样)?

I don't mind if the solution is restricted to Windows boxes only; I also would like the solution to be purely .NET - no p/invokes to CreateThread, etc.

我不介意该解决方案是否仅限于 Windows 设备;我也希望解决方案是纯粹的 .NET - 没有对 CreateThread 等的 p/调用。

Any input appreciated.

任何输入表示赞赏。

采纳答案by Jon Skeet

Use Application.Run- it starts a message loop in the current thread. There are overloads to take a form to start with, or an application context, or neither. (If you want to do this for a newthread, you need to create the thread and start it in the normal way, and make it call Application.Run.)

使用Application.Run- 它在当前线程中启动消息循环。有一些重载可以以某种形式开始,或者一个应用程序上下文,或者两者都没有。(如果要为线程执行此操作,则需要创建该线程并以正常方式启动它,并使其调用Application.Run。)

回答by Adam Robinson

If you're looking to create a new thread that is capable of creating and dealing with Window handles, then you can use the SetApartmentStatefunction on the Thread object and set it to STA. You'll also likely need to call Application.Runinside the method for this thread in order to create your message loop. However, bear in mind that you're subject to the same cross-threading no-no's that you have in any other thread (ie, you can only interact with the handle for a control on the thread inside which it was created), so you can't do anything on your other UI thread without switching contexts.

如果您希望创建一个能够创建和处理 Window 句柄的新线程,那么您可以SetApartmentState在 Thread 对象上使用该函数并将其设置为STA. 您可能还需要Application.Run在该线程的方法内部调用以创建您的消息循环。但是,请记住,您受到与任何其他线程相同的跨线程禁忌(即,您只能与创建它的线程上的控件的句柄进行交互),因此如果不切换上下文,您将无法在其他 UI 线程上执行任何操作。

回答by Erich Mirabal

If you are interested in using WPF, check out MSDN's article WPF's Threading Model, in particular the "Multiple Windows, Multiple Threads" section. It details what you need to do to create a new Dispatcher and show a window on a new thread.

如果您对使用 WPF 感兴趣,请查看 MSDN 的文章WPF 的线程模型,特别是“多窗口,多线程”部分。它详细说明了创建新 Dispatcher 并在新线程上显示窗口所需执行的操作。

回答by galets

Also you can do this:

你也可以这样做:

    delegate void MyProcHandler(object param1, object param2);

    MyForm.Invoke
    (
            new MyProcHandler(delegate(object param1, object param2) 
            {
            // some code
            }), 
            null, 
            null
    );