如何在C#中的不同线程上运行新表单?

SLp*_*SLp 4 .net c# multithreading message-loop winforms

我只是尝试在每次按钮点击时都运行一个新线程,这应该创建一个新表单.我在MainForm中的按钮单击事件中尝试了这个:

private void button1_Click(object sender, EventArgs e)
{
    worker1 = new Thread(new ThreadStart(thread1));
    worker2 = new Thread(new ThreadStart(thread2));

    worker1.Start();
    worker2.Start();
}

private void thread1()
{
    SubForm s = new SubForm();
    s.Show();
}

private void thread2()
{
    SubForm s = new SubForm();
    s.Show();
}
Run Code Online (Sandbox Code Playgroud)

子窗体按钮单击事件中的代码如下所示:

private void button1_Click(object sender, EventArgs e)
{
    int max;
    try
    {
        max = Convert.ToInt32(textBox1.Text);
    }
    catch
    {
        MessageBox.Show("Enter numbers", "ERROR");
        return;
    }

    progressBar1.Maximum = max;

    for ( long i = 0; i < max; i++)
    {
        progressBar1.Value = Convert.ToInt32(i);
    }          
}
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?因为我试图打开两个独立的表单,一个线程中的操作不应该影响另一个线程.

或者BackGroundworker是实现这个的解决方案吗?如果是的话,有人可以帮助我吗?

Tim*_*mwi 13

您不需要在单独的线程中运行表单.您可以s.Show()正常调用多个表单.他们不会互相阻挠.

当然,如果你正在做其他事情,比如某种计算或需要很长时间的其他任务,那么你应该在一个单独的线程中运行,而不是表单.

这里有一些代码可以让您创建一个显示长进程进度的进度条.请注意,每次从线程内部访问表单时,都必须使用.Invoke(),实际上调度该调用在GUI线程准备好时运行.

public void StartLongProcess()
{
    // Create and show the form with the progress bar
    var progressForm = new Subform();
    progressForm.Show();
    bool interrupt = false;

    // Run the calculation in a separate thread
    var thread = new Thread(() =>
    {
        // Do some calculation, presumably in some sort of loop...
        while ( ... )
        {
            // Every time you want to update the progress bar:
            progressForm.Invoke(new Action(
                () => { progressForm.ProgressBar.Value = ...; }));

            // If you’re ready to cancel the calculation:
            if (interrupt)
                break;
        }

        // The calculation is finished — close the progress form
        progressForm.Invoke(new Action(() => { progressForm.Close(); }));
    });
    thread.Start();

    // Allow the user to cancel the calculation with a Cancel button
    progressForm.CancelButton.Click += (s, e) => { interrupt = true; };
}
Run Code Online (Sandbox Code Playgroud)