使用自定义任务工厂创建但不启动任务? [英] Create but not start a task with a custom task factory?

查看:22
本文介绍了使用自定义任务工厂创建但不启动任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在不启动的情况下创建任务,类似于运行 var a = new Task();a.Start(); 但使用自定义工厂.工厂提供了 StartNew(),但是我找不到将这两个操作分开的方法.这可能吗?

I'd like to be able to create a task without starting it, similar to running var a = new Task(); a.Start(); but with a custom factory. Factories provide StartNew(), but I can't find a method to separate the two actions. Is this possible?

推荐答案

TaskFactory 基本上是两组默认选项(创建和延续)、默认取消令牌和任务调度程序.

A TaskFactory is basically two sets of default options (creation and continuation), a default cancellation token, and a task scheduler.

您可以在刚刚新建任务时指定取消令牌和创建选项 - 然后在您想要的任何调度程序上启动它.所以:

You can specify the cancellation token and the creation options when you just new up a task - and then start it on whatever scheduler you want. So:

Task task = new Task(action,
                     factory.CancellationToken,
                     factory.CreationOptions);
...
task.Start(factory.Scheduler);

应该完成除继续选项之外的工作.延续选项仅在您添加延续时才相关,您可以直接指定.是否有任何未涵盖的内容?

should do the job other than continuation options. The continuation options are only relevant when you add a continuation anyway, which you can specify directly. Is there anything which isn't covered by this?

(需要注意的一点是,基于任务的异步模式通常围绕热"任务展开,这些任务无论如何都会在您看到它们时启动.因此,您可能希望避免过于广泛地暴露未启动的任务.)

(One thing to note is that the Task-based Asynchronous Pattern generally revolves around "hot" tasks which are started by the time you see them anyway. So you probably want to avoid exposing the unstarted tasks too widely.)

这篇关于使用自定义任务工厂创建但不启动任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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