为什么我的线程在显示 Windows 窗体后立即终止? [英] Why Does my Thread Terminate Immediately After Showing a Windows Form?

查看:36
本文介绍了为什么我的线程在显示 Windows 窗体后立即终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows 窗体应用程序 (Form1),它允许用户打开另一个窗体 (FormGraph).为了打开 FormGraph 应用程序,我使用了一个线程来打开它.
这是线程正在运行的代码:

I have a Windows Form Application (Form1) that allow the user to open another Forms (FormGraph). In order to open the FormGraph App I use a thread that open it.
Here is the code that the thread is running:

private void ThreadCreateCurvedGraph()
{
    FormGraph myGraph = new FormGraph();
    myGraph.CreateCurvedGraph(...);
    myGraph.Show();
}

我的问题是 myGraph 在打开后立即关闭.
1) 有谁知道为什么会发生这种情况以及如何使 myGraph 保持打开状态?
2) 用户关闭myGraph后,如何终止线程?
非常感谢!

My problem is that myGraph closed right after it's open.
1) Does anyone know why this is happening and how to make myGraph stay open?
2) After the user closed myGraph, How do I terminate the thread?
Many thanks!

推荐答案

问题不在发布的代码段中.您需要使用 Application.Run() 或 Form.ShowDialog() 开始一个新的消息循环.您还需要注意线程属性,使其适合充当 UI 线程.例如:

The problem is not in the posted snippet. You'll need to start a new message loop with Application.Run() or Form.ShowDialog(). You'll also need to take care of thread properties so it is suitable to act as a UI thread. For example:

  Thread t = new Thread(() => {
    Application.Run(new Form2());
    // OR:
    //new Form2().ShowDialog();
  });
  t.SetApartmentState(ApartmentState.STA);
  t.IsBackground = true;
  t.Start();

这里有一些尴尬的选择.该表单不能由主线程上的任何表单拥有,这通常会导致 Z 顺序问题.当 UI 线程的主窗体关闭时,您还需要做一些有意义的事情.此处使用 IsBackground 草率解决.

There are some awkward choices here. The form cannot be owned by any form on your main thread, that usually causes Z-order problems. You'll also need to do something meaningful when the UI thread's main form is closed. Sloppily solved here by using IsBackground.

Windows 旨在支持在一个线程上运行的多个窗口.只有真的必须使用这样的代码.你不应该……

Windows was designed to support multiple windows running on one thread. Only use code like this if you really have to. You should never have to...

这篇关于为什么我的线程在显示 Windows 窗体后立即终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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