使用迭代器等待任务

时间:2013-03-22 16:40:44

标签: c# asp.net parallel-processing task

我正在使用本文Await Tasks in C#4 using Iterators中描述的方法,在没有C#5的情况下尽可能使用asyncawait关键字进行复制。

我偶然发现了一个问题,我认为这个问题与在C#5 see question中使用GetResponseAsync()时常见的问题相同,因为每当我尝试使用等效的扩展方法时yield return跳出IEnumerable<Task>。我没有ConfigureAwait(false)方法。

有人能看到解决这个问题的方法吗?

我的代码:

/// <summary>
/// Processes the image.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> 
/// object that provides references to the intrinsic server objects
/// </param>
private /*async*/ void ProcessImageAsync(HttpContext context)
{
    this.ProcessImageAsyncTask(context).ToTask();
}

/// <summary>
/// Processes the image.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> 
/// object that provides references to the intrinsic server objects
/// </param>
/// <returns>
/// The <see cref="IEnumerable{Task}"/>.
/// </returns>
private IEnumerable<Task> ProcessImageAsyncTask(HttpContext context)
{
    // Code ommited that works out the url
    Uri uri = new Uri(path);

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);

    Task<WebResponse> responseTask = webRequest.GetResponseAsync();
   //################################################################//
   //The method appears to be jumping out of the method here on yield
   //################################################################//
    yield return responseTask;

    // Code that runs other tasks

    yield break;
}

我将相关的扩展方法添加为Github Gist,以使问题更具可读性。

1 个答案:

答案 0 :(得分:0)

我怀疑问题是使用TaskScheduler.FromCurrentSynchronizationContext安排了延续。添加另一个重载以避免这种情况应该相当简单:

public static Task<TResult> ToTask<TResult>(this IEnumerable<Task> tasks, TaskScheduler taskScheduler)
{
    var taskEnumerator = tasks.GetEnumerator();
    var completionSource = new TaskCompletionSource<TResult>();

    // Clean up the enumerator when the task completes.
    completionSource.Task.ContinueWith(t => taskEnumerator.Dispose(), taskScheduler);

    ToTaskDoOneStep(taskEnumerator, taskScheduler, completionSource, null);
    return completionSource.Task;
}

public static Task<TResult> ToTask<TResult>(this IEnumerable<Task> tasks)
{
    var taskScheduler = SynchronizationContext.Current == null
       ? TaskScheduler.Default 
       : TaskScheduler.FromCurrentSynchronizationContext();

    return ToTask<TResult>(tasks, taskScheduler);
}

您的代码将调用另一个重载:

private /*async*/ void ProcessImageAsync(HttpContext context)
{
    ProcessImageAsyncTask(context).ToTask(TaskScheduler.Default);
}