c# - 关于c#中的线程

标签 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() 方法中,我得到一个异常,它说“组合框是从创建它的线程以外的线程访问的”

感谢您的耐心等待... 任何帮助将不胜感激..

最佳答案

这看起来很适合 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 正确。

关于c# - 关于c#中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15832617/

相关文章:

c# - 如何启用特殊键(ctrl-c、ctrl-v、tab、delete)Windows.Form.WebBrowser 控件

c# - 如何将值更新到 appsettings.json 中?

c# - 尝试使用最近创建的文件后程序崩溃。 C#

c# - 多线程文件搜索 C#

multithreading - 多线程访问(读/写)同一个表

c# - WPF ListView - 具有 1 个相同结构的 2 个维度

c# - 12 小时时间格式的正则表达式

c++ - 如何避免 recursive_mutex

c# - 多线程安全日志记录

c++ - C++11 中的基本线程锁定