Can Interlocked.CompareExchange throw NullReferenceException?

后端 未结 2 1521
春和景丽
春和景丽 2021-01-19 00:23

From https://msdn.microsoft.com/en-us/library/bb297966(v=vs.110).aspx

[ComVisibleAttribute(false)]
public static T CompareExchange(
    ref T locati         


        
2条回答
  •  日久生厌
    2021-01-19 00:58

    The documentation is misleading here, as location1 cannot be null since in C# it must always reference an existing variable. So yes, it is ok as what you are saying is "set location1 (that currently contains null) to be src if location1 is already null".

    In fact because location1 has to be a reference it is impossible to pass a null-reference in C#, although it it possible (and valid) to pass a reference to something that is null, and so this function will never throw a NullReferenceException.

    I suspect this is down to the documentation being ported over from the Win32 api, where you have to pass a pointer to the location to read/write the variable, and it would be an error to pass null here.

提交回复
热议问题