【发布时间】:2015-04-19 14:05:45
【问题描述】:
在我的应用程序中,我有两种从 csv 加载数据的方法。这些方法是loadData() 和loadOtherData()。我想并行运行它们,所以我有两个线程来运行它们。
loadData() 方法也填充一个数据网格视图,而loadOtherData() 方法加载的数据存储在字典myDictionary 中。
数据加载完成后(所以两个线程中运行的方法都完成了)我想调用另一个方法updateGrids(),它以myDictionary为参数。
要使updateGrids() 正常运行,loadData() 和loadOtherData() 必须已成功运行,否则该方法没有可处理的数据。
只有当其他方法在其他线程中终止时,我才能调用方法updateGrids()?
结构如下:
private void loadData_Click_1(object sender, EventArgs e)
{
ThreadStart thread1Start = new ThreadStart(loadData); // load data and fill the first datagridview
ThreadStart thread2Start = new ThreadStart(loadOtherData); // load data and fill myDictionary
Thread t1 = new Thread(thread1Start);
Thread t2 = new Thread(thread2Start);
t1.Start();
t2.Start();
updateGrids(myDictionary); // call this method to update remaining datagridviews
}
private void updateGrids(Dictionary<string, double> myDictionary)
{
// update the remaining datagridviews by using
// information in the first datagridview and in myDictionary
}
但如果我运行它,我会在updateGrids() 时收到错误,因为它没有可使用的数据。如何轻松更改代码以使其正常工作?
【问题讨论】:
-
所有工作线程都应该提供检查它们是否完成工作的可能性(简单的计数器就可以了)。在他们的工作结束时,他们应该调用一个方法来检查所有线程工作是否完成并调用
updateGrid()。 -
您使用的是什么版本的 .Net?这会影响答案。
-
谢谢,现在添加到标题中。我正在使用 4.5
-
我从标题中删除了它;标签是此类细节的首选位置。
标签: c# multithreading winforms asynchronous .net-4.5