2

我有一个 C# Windows 应用程序,Form1 上有一个按钮,当按下它时会运行一个很长的程序。在程序运行时,我希望用户界面可用,因此我会将大部分代码放入单独的线程中。作为测试,我将代码放入一个线程并查看它是否有任何问题。我有2个问题。我的最终愿望是让 UI 正常工作,所以如果这不是启动新线程的最佳方式,请告诉我。

首先,虽然程序已编译,但我创建的线程并没有从主线程中看到变量中的所有值。大多数字符串是空的,int 和 float 值为 0。在线程中保持其值的唯一变量是那些使用值创建然后从不更改的变量。显然,我应该能够看到所有变量中的所有值。

其次,我在表单上添加了一个文本框,以便我可以提供有关长时间运行的程序的信息。文本框显示来自主线程的信息没有问题,但我创建的线程中没有显示任何内容。我希望 Form1 上的文本框也可以从线程中更新。

我在 Windows XP 上使用 Visual Studio 2008。

这些是变量的定义。它们位于应用程序的 Program.cs 部分。

partial class Form1
{
    string    TBI_File = "";
    int   junk = 27;

    string junkstr = "Two out of three ain\'t bad";
    double RADD;
    string PROGRAMMER = "Don and Jim"; 
    float  currentSize = 8.25F;        
    float sizechange = 10.0F;  
}

在主线程中(按下按钮后)我创建了新线程。我从http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx复制并修改了这段代码 我评论了 Abort 和 Join 因为在测试的这一点上我想要线程tro 继续运行,直到我单独停止它。

     Wprintf("Alpha.Beta starting");
     Alpha oAlpha = new Alpha();

     // Create the thread object, passing in the Alpha.Beta method
     // via a ThreadStart delegate. This does not start the thread.
     Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

     // Start the thread
     oThread.Start();

     // Spin for a while waiting for the started thread to become
     // alive:
     while (!oThread.IsAlive) ;

     // Put the Main thread to sleep for 1 millisecond to allow oThread
     // to do some work:
     //original
    //Thread.Sleep(1);
     Thread.Sleep(10);

     // Request that oThread be stopped
     //oThread.Abort();

   // Wait until oThread finishes. Join also has overloads
     // that take a millisecond interval or a TimeSpan object.
     //oThread.Join();

     Wprintf("Alpha.Beta has finished");

下面是线程运行的代码。

public class Alpha : Form1
{

    // This method that will be called when the thread is started
    public void Beta()
    {
        while (true)
        {
            //Console.WriteLine("Alpha.Beta is running in its own thread.");
            Wprintf("Alpha.Beta is running in its own thread. " + 
                " RADD: " + RADD + 
                " CurrentSize: " + currentSize.ToString() +
                " TBI_File: " + TBI_File +
                " PROGRAMMER: " + PROGRAMMER +
                " sizechange: " + sizechange.ToString() +
                " junk: " + junk +
                " junkstr: " + junkstr);

           textBox1.AppendText("Alpha.Beta is running in its own thread.");

        }
    }
};

Wprintf 将该消息附加到日志文件并将消息添加到文本框。它适用于整个程序,除了附加到文本框的末尾不适用于创建的线程。我添加了上面的 TextBox1.AppendText(在线程中)以尝试使其工作,但它没有做任何事情,并且线程的文本框中没有显示任何消息。

日志文件的部分如下。日志文件是从线程中附加的,所以我可以看到线程中变量的值(我还查看了调试器中的变量并得到了相同的值)更改的变量是 RADD 和 TBI_FILE,你可以在下面看到RADD 是 0.0 并且 TBI_File 是 '' 在线程中。其他的在程序中没有改变,只是得到了声明时设置的值。

 Alpha.Beta is running in its own thread. RADD: 0  CurrentSize: 8.25 TBI_File:  PROGRAMMER: Don and Jim   sizechange: 10 junk: 27   junkstr: Two out of three ain't bad

我在这里询问了这个问题的早期版本:程序运行时 C# 程序的初始形式不可用

正如我之前指出的,我需要让 UI(文本框并单击 X 退出)可用,所以如果这不是一个好方法,请告诉我。

谢谢,

4

3 回答 3

5

你要考虑的几件事。

最重要的是,您不能从后台线程修改 UI。只有 UI 线程可以修改控件。所以你的textBox1.AppendText行不通。您需要调用 Invoke 以与 UI 线程同步,如下所示:

this.Invoke((MethodInvoker) delegate
    {
        textBox1.Append("Alpha.Beta is running in its own thread.");
    });

当然,这不会更新 UI,因为您的 UI 线程正在等待后台线程完成。

您可能难以管理自己的线程,但最好使用BackgroundWorker,它会为您处理大部分令人讨厌的细节。

// set up the worker
BackgroundWorker worker = new BackgroundWorker();
worker.ReportsProgress = true;
worker.DoWork = worker_DoWork;  // method that's called when the worker starts

// method called to report progress
worker.ProgressChanged = worker_progressChanged;

// method called when the worker is done
worker.RunWorkerCompleted = worker_workCompleted;

// start worker
worker.RunWorkerAsync();


void worker_DoWork(object sender, DoWorkEventArgs e)
{
        //Console.WriteLine("Alpha.Beta is running in its own thread.");
        Wprintf("Alpha.Beta is running in its own thread. " + 
            " RADD: " + RADD + 
            " CurrentSize: " + currentSize.ToString() +
            " TBI_File: " + TBI_File +
            " PROGRAMMER: " + PROGRAMMER +
            " sizechange: " + sizechange.ToString() +
            " junk: " + junk +
            " junkstr: " + junkstr);
    worker.ReportProgress(0, "Alpha.Beta is running in its own thread.");
}

void worker_progressChanged(object sender, ProgressChangedEventArgs e)
{
    textBox1.Append((string)e.UserState);
}

void worker_workCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    textBox1.Append("Worker done!");
}

您的 UI 线程启动工作程序,然后继续。不要让它等待工人完成。如果您想在工作人员完成时收到通知,您可以处理该RunWorkerCompleted事件。或者,如果您只想轮询以查看工作人员是否已完成,您可以让计时器定期检查该IsBusy属性。不过,您最好使用RunWorkerCompleted.

永远不要让你的 UI 线程等待后台线程完成。如果你这样做了,拥有后台线程有什么意义?

于 2013-07-23T19:37:15.780 回答
2

您在 Form 的实例中设置值。然后,您创建一个继承自 Form 的 Alpha 实例,因此也执行 Form 所做的初始化。在 Form 中所做的其他更改将不会在其他实例中显示(不包括静态变量)。您应该更新 Alpha 实例或使用相同的实例。

您不能从除主线程之外的任何线程访问控件。正确的方法是使用 Control.Invoke,例如参见Thread Control.Invoke

此外,以您的方式等待(一段时间)会使主线程卡住。如果您希望等待某事完成 - 您必须处理事件(让工作线程发出信号它已经完成,或者您是后台工作人员并注册 work_completed 事件)。

别的东西 - 你确定要从 Form 继承吗?这真的有必要吗?

于 2013-07-23T19:48:10.313 回答
1

首先,让我针对这种情况给您一些个人建议: 1) 在这种情况下,我宁愿使用 BackgroundWorker 而不是原始的 Thread 类。2) 线程(无论哪种类)不能直接与 UI 或其他线程通信,或者至少它们不应该。

--让我们来回答:由于线程不能/不应该直接访问您的主线程变量,您必须将它们作为参数传递给BackgroundWorker。

下面是一个不言自明的代码,如果您还有任何问题,请在下面评论。

    private BackgroundWorker worker = new BackgroundWorker();
    public Form1()
    {
        InitializeComponent();

        //Register the event/handlers for: Do Work, ProgressChanged, and Worker Completed.
        worker.DoWork += new DoWorkEventHandler(worker_DoWork); 
        worker.WorkerReportsProgress = true; //Let's tell the worker that it WILL be ABLE to report progress.
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); //Method that will be called when the progress has been changed.            
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); //Method that will be called when the thread finish executing.

        //Start the thread async.
        worker.RunWorkerAsync();
    }

    /// <summary>
    /// Method that will run in a new thread async from the main thread.
    /// </summary>        
    /// <param name="e">Arguments that are passed to the Worker Thread (a file, path, or whatever)</param>
    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Get the argument. In this example I'm passing a pathFile.
        string pathFile = (string)e.Argument;

        for (int i = 0; i <= 100; i+=10) //For demonstration purposes we're running from 0 to 99;
        {
            System.Threading.Thread.Sleep(100); //Sleep for demonstration purposes.

            //I want to update the Log, so the user will be notified everytime
            //the log is updated through the ReportProgress event.
            string myLog = i + " ";

            //Invoke the event to report progress, passing as parameter the
            //percentage (i) and the current log the thread has modified.
            worker.ReportProgress(i, myLog);
        }            

        e.Result = "I've made it!!!!! - My complex cientific calculation from NASA is 654.123.Kamehameha)";
    }        

    /// <summary>
    /// Invoked when the worker calls the ReportProgress method.
    /// </summary>        
    /// <param name="e">The arguments that were passed throgh the ReportProgress method</param>
    private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        //Get the Percentage and update the progressbar.
        progressBar1.Value = e.ProgressPercentage;

        //Get the EventArgs and respectively the new log that the thread has modified and append it to the textbox.
        textBox1.AppendText((string)e.UserState);
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Lets check whether the worker has runned successfully (without cancelling and without any errors)
        if (!e.Cancelled && e.Error == null)
        {
            //Lets display the result (Result is an object, so it can return an entire class or any type of data)
            MessageBox.Show((string)e.Result);
        }
    }
于 2013-07-23T19:56:14.360 回答