Is default(CancellationToken) equivalent to Cancel

2019-04-17 23:41发布

Looking at the implementation of CancellationToken.None, it is simply returning default(CancellationToken). However, I see no reference in CancellationToken's documentation that the two are equivalent.

I'd like to offer an API like this but not until I'm sure it'll always work:

Task DoSomething(CancellationToken token = default(CancellationToken))

Is it defined behavior that default(CancellationToken) is the same as CancellationToken.None, or is this just an implementation detail?

4条回答
我想做一个坏孩纸
2楼-- · 2019-04-17 23:46

default is defined for every type. It is null for reference types. It is an "empty" instance for structs, i.e. one with all properties initialized to their respective default values.

查看更多
姐就是有狂的资本
3楼-- · 2019-04-17 23:58

After filing an issue with corefx, the documentation remarks have been updated to make this a guaranteed feature:

You can also use the C# default(CancellationToken) statement to create an empty cancellation token.

查看更多
走好不送
4楼-- · 2019-04-18 00:10

CancellationToken.None simply returns new CancellationToken:

public static CancellationToken None
{    
    get
    {
        return new CancellationToken();
    }
}

Thus CancellationToken is a struct, then default(CancellationToken) will return same value. C# Spec 5.2:

For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor

UPDATE: This behavior is not defined on MSDN, so you can rely only on current implementation.

查看更多
Anthone
5楼-- · 2019-04-18 00:11

They are the same. Check source code

public static CancellationToken None
{
    get { return default(CancellationToken); }
}

From https://referencesource.microsoft.com/#mscorlib/system/threading/CancellationToken.cs,36b17ded8b1a228c

查看更多
登录 后发表回答