关于c#中的线程

时间:2013-04-05 11:21:26

标签: c# multithreading

我点击一下按钮,其中包含十种方法。在这里,我想在按钮单击或代码中的某些位置使用线程,以便我的Windows窗体应用程序不会挂起。

这是我到目前为止所尝试过的...... !!

                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()中,我得到一个异常,说明“除了在”

上创建的线程以外的线程访问组合框

感谢耐心...... 任何帮助将不胜感激..

3 个答案:

答案 0 :(得分:0)

这里你需要的是代表!您只需创建一个委托并将其放在从线程函数访问GUI的函数中。

public delegate void DemoDelegate();

在您的代码中,

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

     // Your Code HERE
}

我希望这会奏效!祝你好运: - )

答案 1 :(得分: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。< / p>

答案 2 :(得分:0)

你应该看看线程池?线程池是一组线程,可用于在后台执行多个任务。它们易于使用且线程安全。

这是一个(非常简单)的例子: http://msdn.microsoft.com/en-us/library/h4732ks0.aspx