我如何在一个新的线程中运行的code简单一点?线程、简单、如何在、code

2023-09-02 11:44:59 作者:若初遇

我有一点code,我需要在不同的线程不是GUI,因为它会导致目前的形式冻结,而在code运行时运行(10秒左右)。

I have a bit of code that I need to run in a different thread than the GUI as it currently causes the form to freeze whilst the code runs (10 seconds or so).

假设我从来没有之前创建一个新的线程;什么是如何做到这一点在C#和使用.NET Framework 2.0或更高版本的简单/基本的例子?

Assume I have never created a new thread before; what's a simple/basic example of how to do this in C# and using .NET Framework 2.0 or later?

推荐答案

的BackgroundWorker 似乎是不错的选择。。

BackgroundWorker seems to be best choice for you.

下面是我的小例子。当您点击按钮的背景工人将开始在后台线程的工作,并同时报告其进展情况。它还将报告工作完成后。

Here is my minimal example. After you click on the button the background worker will begin working in background thread and also report its progress simultaneously. It will also report after the work completes.

using System.ComponentModel;
...
    private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        // this allows our worker to report progress during work
        bw.WorkerReportsProgress = true;

        // what to do in the background thread
        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            // do some simple processing for 10 seconds
            for (int i = 1; i <= 10; i++)
            {
                // report the progress in percent
                b.ReportProgress(i * 10);
                Thread.Sleep(1000);
            }

        });

        // what to do when progress changed (update the progress bar for example)
        bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate(object o, ProgressChangedEventArgs args)
        {
            label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
        });

        // what to do when worker completes its task (notify the user)
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            label1.Text = "Finished!";
        });

        bw.RunWorkerAsync();
    }

注意:

我把一切都放在单一的方法 使用C#的匿名方法 简单,而且可以随时拉 他们到不同的方法。 可以安全地在更新GUI ProgressChanged 或 RunWorkerCompleted 处理程序。 然而,从的DoWork 更新GUI 会造成 InvalidOperationException异常。 I put everything in single method using C#'s anonymous method for simplicity but you can always pull them out to different methods. It is safe to update GUI within ProgressChanged or RunWorkerCompleted handlers. However, updating GUI from DoWork will cause InvalidOperationException.