【问题标题】:Opening a Form on new Thread在新线程上打开表单
【发布时间】:2014-03-23 20:54:27
【问题描述】:

我想在一个新线程上打开一个现有的表单,它有自己的值(在文本字段等中)

这是我的代码:

Dim NewForm As New Form2
NewForm.Textbox1.text = "This is a test"
NewForm.Textbox2.text = "This is the other field"
NewForm.Show()

如何在单独的线程上打开 NewForm

【问题讨论】:

  • 有可能,但你认为你为什么需要这个?
  • 请看c#旁边的VB版本
  • 有可能,但不要这样做。当您认为需要另一个线程时,您就误解了窗口的事件驱动性质。

标签: vb.net multithreading winforms


【解决方案1】:

这只是一个示例代码,如果您已经运行了一个表单,该怎么做

在你的主窗体构造函数中

 // Mark existing thread
 Thread.CurrentThread.Name = "First";
 this.Click += delegate(object a, EventArgs b) { MessageBox.Show(Thread.CurrentThread.Name); };

 // Start new thread
 ThreadStart ts = new ThreadStart(NewThread);
 Thread t = new Thread(ts);
 t.Name = "Second";
 t.Start();

VB

' Mark existing thread
 Thread.CurrentThread.Name = "First"
 AddHandler me.Click, Sub(a As Object, b As EventArgs) MessageBox.Show(Thread.CurrentThread.Name)

 ' Start new thread
 Dim ts As New ThreadStart(NewThread)
 Dim t As New Thread(ts)
 t.Name = "Second"
 t.Start()

现在,打开表单的方法

 private void NewThresd() 
 {

     Form f = new Form();
     f.Text = "dfsdfsdfsdfsd";
     f.Click += delegate(object a, EventArgs b) { MessageBox.Show(Thread.CurrentThread.Name); };
     f.ShowDialog(); 
 }

VB:

Private Sub NewThresd()

    Dim f As New Form()
    f.Text = "dfsdfsdfsdfsd"
    AddHandler f.Click, Sub(a As Object, b As EventArgs) MessageBox.Show(Thread.CurrentThread.Name)
    f.ShowDialog()
End Sub

这将做的是,它将启动一个线程并在其中打开一个表单。当您单击表单时,它将显示线程的名称,以证明您确实在不同的线程上运行表单。

请记住,这不是可用于生产的代码。标记线程并连接单击事件以显示概念。还有,比如这样不好,因为这里会有内存泄漏

f.Click += delegate(object a, EventArgs b) { MessageBox.Show(Thread.CurrentThread.Name); };

你应该在课堂上拥有

private EventHandler _hndlr = delegate(object a, EventArgs b) { MessageBox.Show(Thread.CurrentThread.Name); };

VB

Private _h As EventHandler = Sub(a As Object, b As EventArgs) MessageBox.Show(Thread.CurrentThread.Name)    

然后你连接处理程序

f.Click += _hndlr;

VB

AddHandler f.Click, _hndlr

然后,当关闭表单时 - unwire

f.Click -= _hndlr;

VB

RemoveHandler f.Click, _hndlr

【讨论】:

  • @davidsbro 抱歉,添加了 VB
  • MessageBox.Show() 是一种特殊的静态方法。它是线程安全的,对于这里所问的内容来说不是一个好的测试用例。
  • @HenkHolterman 为什么?它工作得很好,显示线程的正确名称
  • 我没有说它行不通。我说它不演示。
【解决方案2】:

这可以使用Application.run()来完成,例如:

  Dim NewForm As Form2 = New Form2()
                        NewForm.Textbox1.text = "This is a test"
                        NewForm.Textbox2.text = "This is the other field"
                        Application.Run(NewForm)

【讨论】:

  • 你是否熟悉这个错误:Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.??
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多