C#异步和任务

时间:2013-10-13 05:53:41

标签: c#

我有一个函数发送请求以搜索来自网址的信息。搜索条件是一个列表,搜索遍历每个项目并从URL请求信息。为了加快速度,我将列表分成x个子集,并为每个子集创建一个任务。然后每个子集发送3个同时发出的请求,如下所示:

这是主要的切入点:

Search search = new Search();
await Task.Run(() => search.Start());

启动功能:

public void Search()
{
    //Each subset is a List<T> ie where T is certain search criteria
    //If originalList.Count = 30 and max items per subset is 10, then subsets will be 3 lists of 10 items each
    var subsets = CreateSubsets(originalList);

    List<Task> tasks = new List<Task>(subsets.Count);
    for (int i = 0; i < subsets.Count; i++)
        tasks.Add(Task.Factory.StartNew(() => SearchSubset(subsets[i]));

    Task.WaitAll(tasks.ToArray());

    foreach (Task task in tasks)
        if (task != null)
            task.Dispose();
}

private void SearchSubset(List<SearchCriteria> subset)
{
    //Checking that i+1 and i+2 is within subset.Count-1 has been omitted
    for (int i = 0; i < subset.Count; i+=3)
    {
        Task[] tasks = {Task.Factory.StartNew(() => SearchCriteria(subset[i])), 
                        Task.Factory.StartNew(() => SearchCriteria(subset[i+1])),
                        Task.Factory.StartNew(() => SearchCriteria(subset[i+2]))};

        //Wait & dispose like above
    } 
}

private void SearchCriteria(SearchCriteria criteria)
{
    //SearchForCriteria uses WebRequest and WebResponse (callback)
    //to query the url and return the response.content

    var results = SearchForCriteria(criteria);

    //process results...
}

以上代码运行正常,搜索速度非常快。但是,上面的代码是否会产生太多的开销,是否有更清晰(或更简单)的方法来实现相同的结果呢?

1 个答案:

答案 0 :(得分:0)

这不是最有效的方法,但如果这是针对桌面应用程序的,那么效率并不是您最关心的问题。因此,除非您实际看到此代码的性能下降,否则不应更改它。

那就是说,我会以不同的方式接近这一点。

您正在使用TPL来并行化I / O绑定操作。你正在使用最复杂的dynamic parallelism;正如Jeff Mercado评论的那样,如果你使用更高级别的并行抽象,例如Parallel or PLINQ),你的代码会更简单,效率更高。

但是,任何 parallel 方法都会通过阻止它们来浪费线程池线程。由于这是受I / O约束的,我建议使用async / await使它们并发。

如果您想进行简单的限制,可以使用SemaphoreSlim。除了您的子集之外,我认为您不需要像这样进行限制,但如果您希望async等效于现有代码,则它看起来像这样:

public Task SearchAsync()
{
  var subsets = CreateSubsets(originalList);
 return Task.WhenAll(subsets.Select(subset => SearchSubsetAsync(subset)));
}

private Task SearchSubsetAsync(List<SearchCriteria> subset)
{
  var semaphore = new SemaphoreSlim(3);
  return Task.WhenAll(subset.Select(criteria => SearchCriteriaAsync(criteria, semaphore)));
}

private async Task SearchCriteriaAsync(SearchCriteria criteria, SemaphoreSlim semaphore)
{
  await semaphore.WaitAsync();
  try
  {
    // SearchForCriteriaAsync uses HttpClient (async).
    var results = await SearchForCriteriaAsync(criteria);

    // Consider returning results rather than processing them here.
  }
  finally
  {
    semaphore.Release();
  }
}