You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A System.TypeInitializationException may be thrown when an ActivityListener accesses an ActivitySource stored in a static field.
Reproduction Steps
[TestFixture]publicclassDiagnosticsTests{privatestaticclassTelemetry{publicstaticActivitySourceMyActivitySource{get;}=newActivitySource("MyActivitySource");}[Test]publicvoidTest(){ActivitySource.AddActivityListener(newActivityListener{ShouldListenTo= newActivitySource =>{varmyActivitySource=Telemetry.MyActivitySource;// System.TypeInitializationException : The type initializer for 'Telemetry' threw an exception.// ----> System.NullReferenceException : Object reference not set to an instance of an object.// at DiagnosticsTests.Telemetry.get_MyActivitySource()returnnewActivitySource.Name==myActivitySource.Name;},Sample=(refActivityCreationOptions<ActivityContext>_)=>ActivitySamplingResult.AllData,});varactivity=newActivitySource("OtherActivitySource").StartActivity();Assert.That(activity,Is.Null);}}
Expected behavior
Accessing ActivitySource within an ActivityListener should not result in an exception.
Actual behavior
Accessing ActivitySource within an ActivityListener causes a System.TypeInitializationException with an inner NullReferenceException.
The ActivitySource constructor is calling your ShouldListenTo before the field is set, seems like you can't access any ActivitySources inside of a listener.
This is not a bug. The order of the static constructor's initialization is not guaranteed and depends on the runtime. Also, we don't document every issue that can happen because of the order of the static initialization. In your code you can simply do:
Description
A
System.TypeInitializationException
may be thrown when anActivityListener
accesses anActivitySource
stored in a static field.Reproduction Steps
Expected behavior
Accessing
ActivitySource
within anActivityListener
should not result in an exception.Actual behavior
Accessing
ActivitySource
within anActivityListener
causes aSystem.TypeInitializationException
with an innerNullReferenceException
.Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
Issue for docs: dotnet/docs#42745
The text was updated successfully, but these errors were encountered: