How can a default(CancellationToken) have a corresponding CancellationTokenSource

时光怂恿深爱的人放手 提交于 2019-12-05 01:59:36

default(CancellationToken) does create a CancellationToken where m_source is null. You can see that by getting the value of that private field using reflection:

Console.WriteLine(typeof (CancellationToken).
    GetField("m_source", BindingFlags.NonPublic | BindingFlags.Instance).
    GetValue(default(CancellationToken)) ?? "null");

Output:

null

You can also see that by pining only the relevant field in the debugger:

So, what happens?

The debugger, in order to display the contents of the CancellationToken, accesses its properties one by one. When the inner CancellationTokenSource is null the WaitHandle property creates and sets a default CancellationTokenSource before delegating to its WaitHandle property:

public WaitHandle WaitHandle
{
    get
    {
        if (m_source == null)
        {
             m_source = CancellationTokenSource.InternalGetStaticSource(false);
        }

        return m_source.WaitHandle;
    }
}

In conclusion, default(CancellationToken) and new CancellationToken create an empty struct where m_source is null but by looking at the struct in the debugger you are filling that field with a default CancellationTokenSource instance that can't be cancelled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!