【发布时间】:2012-12-01 20:32:03
【问题描述】:
如何合并List<T> 的基于 TPL 的任务以供以后执行?
public async IEnumerable<Task<string>> CreateTasks(){ /* stuff*/ }
我的假设是.Concat() ...
void MainTestApp() // Full sample available upon request.
{
List<string> nothingList = new List<string>();
nothingList.Add("whatever");
cts = new CancellationTokenSource();
delayedExecution =
from str in nothingList
select AccessTheWebAsync("", cts.Token);
delayedExecution2 =
from str in nothingList
select AccessTheWebAsync("1", cts.Token);
delayedExecution = delayedExecution.Concat(delayedExecution2);
}
/// SNIP
async Task AccessTheWebAsync(string nothing, CancellationToken ct)
{
// return a Task
}
我想确保这不会产生任何任务或评估任何东西。事实上,我想我是在问“什么逻辑上执行 IQueryable 到返回数据的东西”?
背景
由于我正在执行递归并且我不想在正确的时间之前执行此操作,如果多次调用合并结果的正确方法是什么?
如果这很重要,我正在考虑运行这个命令来启动所有任务var AllRunningDataTasks = results.ToList();,然后是这个代码:
while (AllRunningDataTasks.Count > 0)
{
// Identify the first task that completes.
Task<TableResult> firstFinishedTask = await Task.WhenAny(AllRunningDataTasks);
// ***Remove the selected task from the list so that you don't
// process it more than once.
AllRunningDataTasks.Remove(firstFinishedTask);
// TODO: Await the completed task.
var taskOfTableResult = await firstFinishedTask;
// Todo: (doen't work)
TrustState thisState = (TrustState)firstFinishedTask.AsyncState;
// TODO: Update the concurrent dictionary with data
// thisState.QueryStartPoint + thisState.ThingToSearchFor
Interlocked.Decrement(ref thisState.RunningDirectQueries);
Interlocked.Increment(ref thisState.CompletedDirectQueries);
if (thisState.RunningDirectQueries == 0)
{
thisState.TimeCompleted = DateTime.UtcNow;
}
}
【问题讨论】:
-
为什么 concat 不工作,它应该工作?另外,你不想运行任务,但运行查询没问题,对吧?
-
@Tilak 我的重点是任务,这是我第一次在任务或查询上这样做。我从来没有在查询中这样做过,但我记得读过 Concat 就是这样做的。
-
@Tilak 也许我在我的代码中发现了一个错误......很快就会更新
标签: linq task-parallel-library ienumerable