C#定期从不同的线程返回值

时间:2010-05-19 11:08:53

标签: c# multithreading

我对多线程很新,缺乏经验。我需要在不同的线程中计算一些数据,这样UI就不会挂起,然后将处理后的数据发送到主窗体上的表中。因此,基本上,用户可以处理已经计算的数据,而其他数据仍在处理中。实现这一目标的最佳方法是什么?我也非常感谢任何例子。提前谢谢。

5 个答案:

答案 0 :(得分:2)

如果您不想使用KMan回答的后台工作人员,您可以自己创建一个帖子。

private void startJob(object work) {
    Thread t = new Thread(
      new System.Threading.ParameterizedThreadStart(methodToCall)
    );
    t.IsBackground = true; // if you set this, it will exit if all main threads exit.
    t.Start(work); // this launches the methodToCall in its own thread.
}

private void methodToCall(object work) {
    // do the stuff you want to do
    updateGUI(result);
}

private void updateGUI(object result) {
    if (InvokeRequired) {
        // C# doesn't like cross thread GUI operations, so queue it to the GUI thread
        Invoke(new Action<object>(updateGUI), result);
        return;
    }
    // now we are "back" in the GUI operational thread.
    // update any controls you like.
}

答案 1 :(得分:1)

签出此BackgroundWorker sample document

答案 2 :(得分:1)

初始化后台工作者对象

BackgroundWorker bw = new BackgroundWorker(); 
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); 

private void bw_DoWork(object sender, DoWorkEventArgs e) 
{ 
    // I need to compute some data in a different thread so the UI doesn't hang up
    // Well! ompute some data here.
    bw.ReportProgress(percentOfCompletion, yourData) // and then send the data as it is processed
    // percentOfCompletion-int, yourData-object(ie, you can send anything. it will be boxed)
}

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
     // to a table on the main form. So, basically, the user can work with the data that is already computed, while other data is still being processed
     List<string> yourData = e.UserState as List<string>; // just for eg i've used a List.
}
  

实现这一目标的最佳方法是什么?

RunWorkerAsync(); //This will trigger the DoWork() method

答案 3 :(得分:0)

使用注册表项在线程之间共享数据

答案 4 :(得分:-1)

您可以将数据发送到静态变量,静态变量可以跨线程共享。