2013-04-05 57 views
2

我有一個按鈕,其中包含十個方法。在這裏,我想使用按鈕點擊或代碼中的某些地方的線程,以便我的Windows窗體應用程序不會掛起。關於c中的線程#

這是我迄今嘗試過的...... !!

   collectListOfPTags(); 

       REqDocCheck = new Thread(new ThreadStart(collectListOfPTags)); 

       REqDocCheck.IsBackground = true; 

       REqDocCheck.Start(); 

       WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) }; 
       while (REqDocCheck.IsAlive) 
       { 
        WaitHandle.WaitAny(AWait, 50, false); 
        System.Windows.Forms.Application.DoEvents(); 
       } 

collectionListOfPtags()我得到一個異常,說的方法「的組合框從其它線程訪問比它是在創建」

感謝對耐心.. 任何幫助將不勝感激..

+2

有一個很好的介紹到這裏螺紋:['Albahari'(http://www.albahari.com/threading/) – 2013-04-05 11:22:51

+3

您不能訪問一個GUI從主線程以外的其他線程進行控制。有關於SO的19861353帖子關於那個...搜索它(http://stackoverflow.com/search?q=gui+thread) – derape 2013-04-05 11:24:03

+0

@NicholasButler我已經經歷了那個..!感謝您的回覆 – 2013-04-05 11:24:26

回答

0

這看起來很適合BackgroundWorker組件。

將您的collectListOfPTags方法拆分爲2個方法 - 第一個方法收集並處理數據,第二個方法更新UI控件。

事情是這樣的:

void OnClick(...) 
{ 
    var results = new List<string>(); 

    var bw = new BackgroundWorker(); 

    bw.DoWork += (s, e) => CollectData(results); 
    bw.RunWorkerCompleted += (s, e) => UpdateUI(results); 

    bw.RunWorkerAsync(); 
} 

void CollectData(List<string> results) 
{ 
    ... build strings and add them to the results list 
} 

void UpdateUI(List<string> results) 
{ 
    ... update the ComboBox from the results 
} 

BackgroundWorker將在一個線程池線程後臺運行CollectData,但會在UI線程上運行UpdateUI這樣你就可以正確地訪問ComboBox

0

您需要的是代表!您只需創建一個委託並將其放入從線程函數訪問GUI的函數中即可。

public delegate void DemoDelegate(); 

在你的代碼,

collectionListOfPtags() 
{ 
    if ((this.InvokeRequired)) { 
    this.Invoke(new DemoDelegate(collectionListOfPtags)); 
    return; 
    } 

    // Your Code HERE 
} 

我希望這將工作!好運:-)