2010-05-19 40 views
2

我對多線程很陌生,缺乏經驗。我需要在不同的線程中計算一些數據,以便UI不會掛起,然後在處理數據時將它們發送到主表單上的表格。因此,基本上,用戶可以使用已經計算的數據,而其他數據仍在處理中。達到此目的的最佳方法是什麼?我也非常感謝任何例子。提前致謝。C#定期從不同的線程返回值

+2

搜索棧溢出了「的BackgroundWorker」這應該給你很多好的答案的問題之間共享數據。 – ChrisF 2010-05-19 11:11:46

+2

或者查看[BackgroundWorker MSDN頁面](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) – ChrisF 2010-05-19 11:12:32

回答

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 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 
+0

感謝@Kate Gregory爲消除不必要的東西:)。 – Amsakanna 2013-07-22 09:26:53

0

使用註冊表項添加到線程

+0

有點遲到了嗎? – Cyral 2012-06-22 13:42:56

+0

如果他們有用,答案永遠不會遲到。 – mydogisbox 2012-06-25 17:23:29

+0

請注意,請不要嘗試使用註冊表來實現進程中的線程之間的通信。 – reuben 2012-07-14 06:29:24