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)
yields
A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'System.Threading.CancellationToken'
and
Task<x> DoStuff(...., CancellationToken ct = CancellationToken.None)
Default parameter value for 'ct' must be a compile-time constant
Is there any way to have a default value for CancellationToken
?
It turns out that the following works:
Task<x> DoStuff(...., CancellationToken ct = default(CancellationToken))
...or:
Task<x> DoStuff(...., CancellationToken ct = default) // C# 7.1 and later
which, according to the documentation, is interpreted the same as CancellationToken.None
:
You can also use the C#
default(CancellationToken)
statement to create an empty cancellation token.