CancellationToken的默认参数 [英] Default parameter for CancellationToken
问题描述
我有一些异步代码,想向其中添加 CancellationToken
。但是,在许多实现中不需要此实现,因此我想使用一个默认参数-也许 CancellationToken.None
。但是,
I have some async code that I would like to add a CancellationToken
to. However, there are many implementations where this is not needed so I would like to have a default parameter - perhaps CancellationToken.None
. However,
Task<x> DoStuff(...., CancellationToken ct = null)
收益率
类型''的值不能用作默认参数,因为
没有对
类型的标准转换'System.Threading.CancellationToken'
A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'System.Threading.CancellationToken'
和
Task<x> DoStuff(...., CancellationToken ct = CancellationToken.None)
'ct'的默认参数值必须是编译时常量
Default parameter value for 'ct' must be a compile-time constant
有没有办法为<$ c提供默认值$ c> CancellationToken ?
推荐答案
事实证明,以下方法有效:
It turns out that the following works:
Task<x> DoStuff(...., CancellationToken ct = default(CancellationToken))
其中,根据文档,与 CancellationToken.None
解释相同:
您也可以使用C#
default(CancellationToken)
语句可创建
一个空的取消令牌。
You can also use the C#
default(CancellationToken)
statement to create an empty cancellation token.
这篇关于CancellationToken的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!