How can by default (CancellationToken) have the corresponding CancellationTokenSource

When I create a default CancellationToken , I see in the debugger that the CancellationToken has a CancellationToken associated with it, which is stored in a private m_source :

Not null

I am wondering how this could be the case for structs default keyword "will return each member of the structure, initialized to zero or zero, depending on whether they are values ​​or reference types" and CancellationTokenSource is a reference type.

CancellationToken has 2 constructors that set this field, however they are irrelevant, since default(CancellationToken) does not call constructors, and new CancellationToken() (which has the same behavior) does not call the constructor, because structures cannot have parameterless constructors ( so far )

+8
c # cancellationtokensource
Mar 30 '15 at 19:58
source share
1 answer

default(CancellationToken) creates a CancellationToken , where m_source is null . You can see that by getting the value of this 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 this by deleting only the corresponding field in the debugger:

null

So what is going on?

The debugger, in order to display the contents of the CancellationToken , accesses its properties one by one. When the internal CancellationTokenSource is null , the WaitHandle property creates and sets the default CancellationTokenSource before passing it to the 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 structure where m_source is null , but looking at the structure in the debugger you fill this field with the default instance of CancellationTokenSource , which cannot be undone.

+11
Mar 30 '15 at 19:58
source share



All Articles