如何使用任务在一个线程中执行循环的每个迭代? [英] How to execute each iteration of the loop in one thread with task?
问题描述
我有一个检查某些数据的方法,我想知道如何在不同的线程中检查这些数据.我正在使用任务和异步/等待模式.
I have a method that check some data and I would like to know how to check this data in differents threads. I am using task and async/await pattern.
private bool my myCheckMethod(List<long> paramData)
{
//code that check the information in the list
}
private void mainMethod()
{
//1.- get data from the data base
//2.- i group the data from the database in many lists.
foreach(list<List<long>> iterator in myListOfLists)
{
myCheckMethod(itrator);
}
}
但是我希望myCheckMethod不能一次只执行一个,而是要使用任务来同时执行多个任务.我认为这会花更少的时间.
But I would like that the myCheckMethod not execute only one at time, but to use tasks to execute many at same time. I think that it would take less time.
但是,我不知道该怎么做.我尝试这样的事情:
However, I don't know well how to do that. I try something like that:
private void mainMethod()
{
//1.- get data from the data base
//2.- i group the data from the database in many lists.
string initTime = System.DateTime.String();
foreach(list<List<long>> iterator in myListOfLists)
{
myCheckMethod(itrator);
}
string endTime = System.DateTime.String();
}
我想在开始检查以及检查所有列表时获得信息.
I would like to have information when the check is started and when all the lists are checked.
我尝试这样的事情:
private void mainMethod()
{
//1.- get data from the data base
//2.- i group the data from the database in many lists.
string startTime = System.DateTime.String();
foreach(list<List<long>> iterator in myListOfLists)
{
TaskEx.Run(() =>
{
myCheckMethod(itrator);
});
}
string endTime = System.DateTime.String();
}
但是在这种情况下,开始时间和结束时间是相同的,因为我不等待任务.因此,我尝试了另一种选择:
But in this case start time and end time is the same, because I don't await the task. So I try this other option:
private void mainMethod()
{
//1.- get data from the data base
//2.- i group the data from the database in many lists.
string startTime = System.DateTime.String();
foreach(list<List<long>> iterator in myListOfLists)
{
TaskEx.Run(() =>
{
myCheckMethod(itrator);
}).wait();
}
string endTime = System.DateTime.String();
}
但是在这种情况下,一次只能执行一个myCheckMethod,因为我想完成一个myCheckMethod来继续下一次迭代.
But in this case only is executed one myCheckMethod at the same time, because I am wating to finish one to continue with the next iteration.
那我怎样才能同时执行许多检查方法呢?
So how can I execute many check methods at the same time?
推荐答案
var sw = Stopwatch.StartNew();
var pendingTasks =
myListOfLists
.Select(iterator => TaskEx.Run(() => myCheckMethod(iterator))).ToArray();
Task.WaitAll(pendingTasks);
var elapsedTime = sw.Elapsed;
这篇关于如何使用任务在一个线程中执行循环的每个迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!