How can a new Form be run on a different thread in C#?

前端 未结 4 1020
野的像风
野的像风 2021-01-01 06:27

I\'m just trying to run a new thread each time a button click even occurs which should create a new form. I tried this in the button click event in the MainForm:



        
4条回答
  •  一生所求
    2021-01-01 06:38

    You do not need to run forms in separate threads. You can just call s.Show() on multiple forms normally. They will not block each other.

    Of course, if you’re doing something else, like some sort of calculation or other task that takes a long while, then you should run that in a separate thread, but not the form.

    Here is a bit of code that will let you create a progress bar that shows progress for a long process. Notice that every time to access the form from inside the thread, you have to use .Invoke(), which actually schedules that invocation to run on the GUI thread when it’s ready.

    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; };
    }
    

提交回复
热议问题