问题描述
我有一些方法返回任务< T>
上,我可以等待
的意愿。我想有一个自定义执行这些任务的TaskScheduler
而不是默认的。
I have some methods returning Task<T>
on which I can await
at will. I'd like to have those Tasks executed on a custom TaskScheduler
instead of the default one.
var task = GetTaskAsync ();
await task;
我知道我可以创建一个新的 TaskFactory(新CustomScheduler())
,并做了 StartNew()
从它,但 StartNew()
采取的行动,并创建工作
,我已经有工作
(由幕后返回 TaskCompletionSource
)
I know I can create a new TaskFactory (new CustomScheduler ())
and do a StartNew ()
from it, but StartNew ()
takes an action and create the Task
, and I already have the Task
(returned behind the scenes by a TaskCompletionSource
)
我怎么可以指定自己的的TaskScheduler
为等待
?
How can I specify my own TaskScheduler
for await
?
推荐答案
我想你真正想要的是做一个 Task.Run
,但有一个自定义的调度。 StartNew
不与异步方法直观地工作;斯蒂芬Toub有大约 任务之间的差异.RUN
和 TaskFactory.StartNew
。
I think what you really want is to do a Task.Run
, but with a custom scheduler. StartNew
doesn't work intuitively with asynchronous methods; Stephen Toub has a great blog post about the differences between Task.Run
and TaskFactory.StartNew
.
所以,要创建自己的自定义运行
,你可以做这样的事情:
So, to create your own custom Run
, you can do something like this:
private static readonly TaskFactory myTaskFactory = new TaskFactory(
CancellationToken.None, TaskCreationOptions.DenyChildAttach,
TaskContinuationOptions.None, new MyTaskScheduler());
private static Task RunOnMyScheduler(Func<Task> func)
{
return myTaskFactory.StartNew(func).Unwrap();
}
private static Task<T> RunOnMyScheduler<T>(Func<Task<T>> func)
{
return myTaskFactory.StartNew(func).Unwrap();
}
private static Task RunOnMyScheduler(Action func)
{
return myTaskFactory.StartNew(func);
}
private static Task<T> RunOnMyScheduler<T>(Func<T> func)
{
return myTaskFactory.StartNew(func);
}
然后就可以执行同步的或的异步方法上的自定义调度。
Then you can execute synchronous or asynchronous methods on your custom scheduler.
这篇关于如何运行使用计谋自定义的TaskScheduler任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!