带有TaskCompletionSource的TaskCreationOptions的目的是什么? [英] What is the purpose of TaskCreationOptions with a TaskCompletionSource?
问题描述
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屋!