Default parameter for CancellationToken

前端 未结 6 2083
猫巷女王i
猫巷女王i 2021-02-06 20:05

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 d

6条回答
  •  失恋的感觉
    2021-02-06 20:52

    Is there any way to have a default value for CancellationToken?

    Unfortunately, this is not possible, as CancellationToken.None is not a compile time constant, which is a requirement for default values in optional arguments.

    You can provide the same effect, however, by making an overloaded method instead of trying to use default parameters:

    Task DoStuff(...., CancellationToken ct)
    {
        //...
    }
    
    Task DoStuff(....)
    {
        return DoStuff(...., CancellationToken.None);
    }
    

提交回复
热议问题