我有一个按钮点击,其中包含大约十种方法。在这里,我想在按钮点击或代码中的某些地方使用线程,这样我的 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/