如何在一个线程中打开窗体,并迫使它继续开放 [英] How to open a form in a thread and force it to stay open

查看:177
本文介绍了如何在一个线程中打开窗体,并迫使它继续开放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然有问题搞清楚如何在我讨论<一个独立的UI线程创建的WinForms href="http://stackoverflow.com/questions/164789/winforms-implementation-question-for-having-my-ui-run-independently-of-my-bll-l">here.

在试图弄清楚这一点,我写了下面的简单的测试程序。我只是希望它的命名为UI线程一个单独的线程中打开窗体,并保持只要同时允许用户与表单交互(纺纱是欺骗)的形式是开放运行的线程。我明白了为什么下面的失败和线程立即关闭,但我不知道是我应该做的,以修复它。

 使用系统;
使用System.Windows.Forms的;
使用的System.Threading;

命名空间UIThreadMarshalling {
    静态类节目{
    [STAThread]
    静态无效的主要(){
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(假);
    变种TT =新ThreadTest();
    的ThreadStart TS =新的ThreadStart(tt.StartUiThread);
    线程t =新主题(TS);
    t.Name =UI线程;
    t.Start();
    Thread.sleep代码(新时间跨度(0,0,10));
    }

    }

    公共类ThreadTest {
    形成_form;
    公共ThreadTest(){
    }

    公共无效StartUiThread(){
    _form =新Form1中();
    _form.Show();
    }
    }
}
 

解决方案

在一个新的线程,调用Application.Run传递表单对象,这将使线程中运行自己的消息循环,而窗口已打开。

然后就可以调用。加入该线程,使你的主线程等待,直到UI线程已经终止,或者使用类似的技巧,等待该线程完成。

例如:

 公共无效StartUiThread()
{
    使用(Form1中_form =新Form1中())
    {
        Application.Run(_form);
    }
}
 

I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed here.

In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it.

using System;
using System.Windows.Forms;
using System.Threading;

namespace UIThreadMarshalling {
    static class Program {
    	[STAThread]
    	static void Main() {
    		Application.EnableVisualStyles();
    		Application.SetCompatibleTextRenderingDefault(false);
    		var tt = new ThreadTest();
    		ThreadStart ts = new ThreadStart(tt.StartUiThread);
    		Thread t = new Thread(ts);
    		t.Name = "UI Thread";
    		t.Start();
    		Thread.Sleep(new TimeSpan(0, 0, 10));
    	}

    }

    public class ThreadTest {
    	Form _form;
    	public ThreadTest() {
    	}

    	public void StartUiThread() {
    		_form = new Form1();
    		_form.Show();
    	}
    }
}

解决方案

On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.

Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.

Example:

public void StartUiThread()
{
    using (Form1 _form = new Form1())
    {
        Application.Run(_form);
    }
}

这篇关于如何在一个线程中打开窗体,并迫使它继续开放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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