如何使用等待在自定义 TaskScheduler 上运行任务? [英] How to run a Task on a custom TaskScheduler using await?
问题描述
我有一些返回 Task
的方法,我可以在这些方法上随意await
.我想让这些任务在自定义 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 (new CustomScheduler ())
并从中做一个 StartNew ()
,但是 StartNew ()
> 采取行动并创建Task
,我已经有了Task
(由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
)
如何为 await
指定我自己的 TaskScheduler
?
How can I specify my own TaskScheduler
for await
?
推荐答案
我认为您真正想要的是使用自定义调度程序执行 Task.Run
.StartNew
不适用于异步方法;Stephen Toub 有一篇很棒的博客文章,关于 之间的差异Task.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
.
因此,要创建您自己的自定义Run
,您可以执行以下操作:
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 上运行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!