2013-08-22 18 views
-2

我的問題很簡單,我的SQL查詢需要2分鐘才能完成,我不能讓我的應用程序在嘗試獲取所有數據時被凍結。我嘗試了多線程,但是我一直在遇到一個我很確定你會認識的錯誤。我的代碼就在這個下面。在線程中加載數據

跨線程操作無效:從其創建的線程以外的線程訪問的控件'labelEdit1'。

private void Form_Load(object sender, EventArgs e) 
    { 
     startup = new Thread(loadInThread); 
     startup.Start();    
    } 

private void loadInThread() 
{ 
    //getsDataFromSQL() is the method that takes over 2 minutes to do 
    //it returns a String Array if that is helpful 
    comboEdit1.Properties.Items.AddRange(getsDataFromSQL()); 
    startup.Abort(); 
} 

如果有更好的方法來做到這一點,那麼請讓我知道,我需要的是爲應用程序不會凍結起來,這些數據取得裝入comboEdit。我也知道SQL語句可以優化,但這不是這個問題的關鍵,所以請不要提示它。

+0

您是否對交叉線程異常做過任何研究?這個問題的第一個相關問題有標題「跨線程操作無效:控制訪問從一個線程以外的線程創建它」... –

+0

http://stackoverflow.com/questions/142003/cross -thread-operation-not-valid-control-accessible-from-a-thread-other-than-the-rq = 1 –

+0

-1缺少研究 –

回答

1

您需要在這裏使用調度程序。這是因爲你不能從另一個線程訪問UI線程擁有的控件。檢查這個鏈接here。我沒有檢查過這個編譯錯誤,但是這個應該會對你做一些小小的修改。

private void loadInThread() 
{ 
    //getsDataFromSQL() is the method that takes over 2 minutes to do 
    //it returns a String Array if that is helpful 
    comboEdit1.Dispatcher.BeginInvoke((Action)(() => 
    { 
     comboEdit1.Properties.Items.AddRange(getsDataFromSQL()); 
    })); 
    startup.Abort(); 
} 
+0

現在出現錯誤,說comboEdit1沒有Dispatcher方法。這可能是因爲我使用了Devexpress組合框? –

+0

嘗試使用「Dispatcher.BeginInvoke」而不是「comboEdit1.Dispatcher.BeginInvoke」。只是FYI,在.NET Framework 3和更高版本中引入的Dispatcher位於System.Windows.Threading命名空間中,而不是System.Threading中。 – samar

1

你是怎麼做多線程的?您是否手動創建線程?不要這樣做。我建議用以下三種方法之一去:

  1. async/await - http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx(.NET 4.5 +只)
  2. 任務並行庫 - http://msdn.microsoft.com/en-us/library/dd460717.aspx(.NET 4.0 +只)
  3. BackgroundWorker - http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

手動處理線程邏輯當然也是可以的。在這種情況下,您可能需要查看BeginInvoke方法:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx