C# 从另一个线程调用 form.show()

C# 从另一个线程调用 form.show()

问题描述:

如果我从另一个线程对 WinForms 对象调用 form.show(),该表单将抛出异常.有什么方法可以向主应用程序线程添加新的可见表单?否则,如何在不停止当前正在执行的线程的情况下打开表单?

if I call form.show() on a WinForms object from another thread, the form will throw an exception. Is where any way I can add a new, visible form to the main app thread? Otherwise, how can I open the form without stopping my currently executing thread?

这是我的示例代码.我正在尝试启动一个线程,然后在该线程中执行一些工作.随着工作的进行,我会展示表格.

Here is my sample code. I am attempting to start a thread and then execute some work within that thread. As the work progresses, I will show the form.

public void Main()
{
    new Thread(new ThreadStart(showForm)).Start();
    // Rest of main thread goes here...
}

public void showForm() 
{
    // Do some work here.
    myForm form = new myForm();
    form.Text = "my text";
    form.Show();
    // Do some more work here
}

尝试使用调用:

public static Form globalForm;

void Main()
{
    globalForm = new Form();
    globalForm.Show();
    globalForm.Hide();
    // Spawn threads here
}

void ThreadProc()
{
    myForm form = new myForm();
    globalForm.Invoke((MethodInvoker)delegate() {
        form.Text = "my text";
        form.Show();
    });
}

invoke"调用告诉表单请在您的线程而不是我的线程中执行此代码."然后,您可以从委托中更改 WinForms UI.

The "invoke" call tells the form "Please execute this code in your thread rather than mine." You can then make changes to the WinForms UI from within the delegate.

关于 Invoke 的更多文档在这里:http://msdn.microsoft.com/en-us/图书馆/zyzhdc6b.aspx

More documentation about Invoke is here: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx

您需要使用一个已经存在的 WinForms 对象来调用 invoke.我在这里展示了如何创建全局对象;否则,如果您有任何其他 Windows 对象,它们也可以正常工作.

You will need to use a WinForms object that already exists in order to call invoke. I've shown here how you can create a global object; otherwise, if you have any other windows objects, those will work as well.