11// ReSharper disable PossibleInvalidOperationException
22
3+ using System . Diagnostics ;
4+
35namespace Universe . CpuUsage
46{
57 using System ;
68 using System . Collections . Generic ;
7- using System . Diagnostics ;
89 using System . Text ;
910 using System . Threading ;
1011 using System . Linq ;
@@ -16,6 +17,8 @@ public ICollection<ContextSwitchMetrics> Totals
1617 {
1718 get
1819 {
20+ // always not null
21+ if ( _Log == null ) return new List < ContextSwitchMetrics > ( ) ;
1922 lock ( _Log )
2023 {
2124 return new List < ContextSwitchMetrics > ( _Log ) ;
@@ -38,6 +41,11 @@ public class ContextSwitchMetrics
3841 public void Stop ( )
3942 {
4043 IsRunning = false ;
44+ #if ! NET20 && ! NET30 && ! NET35 && ! NET40 && ! NET45
45+ _ContextSwitchListener . Value = null ;
46+ _ContextSwitchListener = null ;
47+ #endif
48+ // _Log = null; it is the results
4149 }
4250
4351#if NETSTANDARD1_3 || NETSTANDARD1_4 || NETSTANDARD1_5 || NETSTANDARD1_6
@@ -46,7 +54,7 @@ public void Stop()
4654#else
4755 static long GetThreadId ( ) => Thread . CurrentThread . ManagedThreadId ;
4856 public static bool IsSupported => CpuUsageReader . IsSupported && IsFrameworkSupported ;
49- #endif
57+ #endif
5058
5159
5260// legacy net framework [2.0 ... 4.6) is not supported
@@ -82,12 +90,13 @@ private void ContextChangedHandler(AsyncLocalValueChangedArgs<object> args)
8290 }
8391 else if ( args . CurrentValue == null )
8492 {
85- var contextOnStart = ContextItem . Value ;
93+ ContextSwitchInfo contextOnStart = ContextItem . Value ;
8694 ContextItem . Value = null ;
8795 if ( contextOnStart == null )
8896 {
8997 // .Stop() lost, Force Stop()
9098 IsRunning = false ;
99+ Stop ( ) ;
91100 return ;
92101 // throw new InvalidOperationException("CpuUsageAsyncWatcher.OnEnd: Missing contextOnStart. Please report");
93102 }
@@ -115,13 +124,13 @@ private void ContextChangedHandler(AsyncLocalValueChangedArgs<object> args)
115124 Console . ForegroundColor = ConsoleColor . Cyan ;
116125 string AsString ( object value ) => value == null ? "off" : Convert . ToString ( value ) ;
117126 Console . WriteLine ( $ "Value Changed { ( args . ThreadContextChanged ? $ "WITH context #{ tid } " : $ "WITHOUT context #{ tid } ") } : { AsString ( args . PreviousValue ) } => { AsString ( args . CurrentValue ) } ") ;
118- #endif
127+ #endif
119128 }
120129
121130 public CpuUsageAsyncWatcher ( )
122131 {
123132 _ContextSwitchListener = new AsyncLocal < object > ( ContextChangedHandler ) ;
124- _ContextSwitchListener . Value = "Online" ;
133+ _ContextSwitchListener . Value = new object ( ) ; // "Online" does not occupies additional memory
125134 }
126135
127136#else
0 commit comments