2013-04-05 58 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 
} 

我希望这将工作!好运:-)