【发布时间】:2011-08-28 23:33:52
【问题描述】:
我有以下情况:
我的应用程序必须从另一个应用程序导入多组数据,时间很关键。
因此,它为每次导入生成一个线程。
所以,假设我有 1 到 10 的进口,其中进口 4 和 5 只能在进口 2 之后的进口 1、6 和 7 以及进口 3 之后的 8、9 和 10 之后运行
- 导入 1
- 导入4
- 导入5
- 导入 2
- 导入6
- 导入7
- 导入 3
- 导入8
- 导入9
- 导入10
搜索 stackoverflow 我发现了一些关于等待句柄的答案,但我不确定控制多个等待句柄。
我想创建一个导入/句柄列表并在循环中检查它们,但我不知道如何从那里触发 .set()。
或者为每个父导入创建一个线程并在其中实例化句柄,并且该父线程为每个子导入触发一个线程,但是我不确定处理线程的线程是否正确。
关于如何解决这个问题的任何想法?
更新:
在 Brian Gideon 的回答之后,我想到了:dateSince = Convert.ToDateTime(txtBoxDateSince.Text);
dateTo = Convert.ToDateTime(txtBoxDateTo.Text);
//在时间间隔上循环所有天 而 (DateTime.Compare(dateSince, dateTo)
foreach (ListItem father in checkBoxListFather.Items)
{
if (father.Selected == true)
{
processClass process = new processClass();
// This WaitHandle will be used to get the child tasks going.
var wh = new ManualResetEvent(false);
//Method to Import, wraped in a delegate
WaitCallback fatherMethod = new WaitCallback(process.importProcess);
//and its parameters
processClass.importParameters param = new processClass.importParameters(wh, father.Value, null, dateSince);
// Queue the parent task.
ThreadPool.QueueUserWorkItem(fundMethod, param);
// Register the child tasks.
foreach (ListItem child in checkBoxListChild.Items)
{
if (child.Selected == true)
{
processClass.importParameters parameters = new processClass.importParameters(null, child.Value, null, dateSince);
// Registers a callback for the child task that will execute once the
// parent task is complete.
WaitOrTimerCallback childMethod = new WaitOrTimerCallback(process.anotherImportProcess);
RegisteredWaitHandle rwh = ThreadPool.RegisterWaitForSingleObject(wh, childMethod, parameters, Timeout.Infinite, true);
}//End if (child.Selected == true)
}//End foreach (ListItem fund in checkBoxListChild.Items)
}//End if (father.Selected == true)
}//End foreach (ListItem fundProcess in checkBoxListFather.Items)
dateSince = dtSince.AddDays(1);
}//结束 while (DateTime.Compare(since,to)
几乎相同的答案,只是使用了没有 lambda 表达式的方法并在它们上使用了参数。
我仍然没有对它进行压力测试,但它工作得很好。
谢谢布赖恩。
【问题讨论】:
标签: multithreading .net-3.5 synchronization asp.net-3.5