带有TaskCompletionSource的TaskCreationOptions的目的是什么? [英] What is the purpose of TaskCreationOptions with a TaskCompletionSource?

查看:149
本文介绍了带有TaskCompletionSource的TaskCreationOptions的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TaskCompletionSource<>的内部运作方式对我来说还不清楚.

There's something unclear to me about the inner workings of TaskCompletionSource<>.

当使用Factory创建简单的Task<>时,我希望此任务被放入线程池中,除非我指定TaskCreationOptions.LongRunning,否则它将在新线程中运行.

When creating a simple Task<> using the Factory, I expect this task to be enqueued in a thread pool, unless I specify TaskCreationOptions.LongRunning, where it will run in a new thread instead.

我对TaskCompletionSource的理解是,我负责在任务结束或失败时触发,并且对如何管理线程拥有完全控制权. 但是,TaskCompletionSource的ctor允许我指定TaskCreationOptions,这使我感到困惑,因为我期望Scheduler无法自己处理任务.

My understanding of TaskCompletionSource, is that I am responsible of triggering when a task ends, or fails, and I have full control on how to manage threads. However, the ctor of TaskCompletionSource allows me to specify a TaskCreationOptions, and this confuse me, since I was expecting the Scheduler not being able to handle the task itself.

TaskCompletionSource<>上下文中TaskCreationOptions的目的是什么?

What is the purpose of TaskCreationOptions in the context of a TaskCompletionSource<>?

以下是使用示例:

public Task<WebResponse> Download(string url)
{
    TaskCompletionSource<WebResponse> tcs = 
    new TaskCompletionSource<WebResponse>(TaskCreationOptions.LongRunning);

    var client = (HttpWebRequest)HttpWebRequest.Create(url);
    var async = client.BeginGetResponse(o =>
      {
          try
          {
              WebResponse resp = client.EndGetResponse(o);
              tcs.SetResult(resp);
          }
          catch (Exception ex)
          {
              tcs.SetException(ex);
          }
      }, null);


    return tcs.Task;
}

推荐答案

答案是TaskCreationOption仅对其AttachToParent选项有用,因为TaskCompletionSource可以是任何其他任务的子级. 与线程管理或执行顺序相关的选项与TaskCompletionSource的上下文无关.以下代码实际上引发异常:

The answer is that a TaskCreationOption is useful for its AttachToParent option only, as TaskCompletionSource can be the child of any other task. Options related to thread management or execution ordering aren't relevant in the context of a TaskCompletionSource. The following code actually throws an exception:

new TaskCompletionSource<WebResponse>(TaskCreationOptions.LongRunning);

这篇关于带有TaskCompletionSource的TaskCreationOptions的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆