@@ -701,8 +701,8 @@ private static string ReviseThreadName(string? threadName)
701701 /// </value>
702702 /// <remarks>
703703 /// <para>
704- /// Calls <c>WindowsIdentity.GetCurrent().Name</c> to get the name of
705- /// the current windows user.
704+ /// On Windows it calls <c>WindowsIdentity.GetCurrent().Name</c> to get the name of
705+ /// the current windows user. On other OSes it calls Environment.UserName.
706706 /// </para>
707707 /// <para>
708708 /// To improve performance, we could cache the string representation of
@@ -743,17 +743,26 @@ private static string ReviseThreadName(string? threadName)
743743
744744 private string ? TryGetCurrentUserName ( )
745745 {
746- if ( _platformDoesNotSupportWindowsIdentity )
747- {
748- // we've already received one PlatformNotSupportedException
749- // and it's highly unlikely that will change
750- return Environment . UserName ;
751- }
752-
753746 try
754747 {
755- return _cachedWindowsIdentityUserName ??=
756- TryReadWindowsIdentityUserName ( ) ;
748+ if ( _platformDoesNotSupportWindowsIdentity )
749+ {
750+ // we've already received one PlatformNotSupportedException or null from TryReadWindowsIdentityUserName
751+ // and it's highly unlikely that will change
752+ return Environment . UserName ;
753+ }
754+
755+ if ( _cachedWindowsIdentityUserName is not null )
756+ {
757+ return _cachedWindowsIdentityUserName ;
758+ }
759+ if ( TryReadWindowsIdentityUserName ( ) is string userName )
760+ {
761+ _cachedWindowsIdentityUserName = userName ;
762+ return _cachedWindowsIdentityUserName ;
763+ }
764+ _platformDoesNotSupportWindowsIdentity = true ;
765+ return Environment . UserName ;
757766 }
758767 catch ( PlatformNotSupportedException )
759768 {
@@ -777,12 +786,21 @@ private static string ReviseThreadName(string? threadName)
777786 }
778787
779788 private string ? _cachedWindowsIdentityUserName ;
780- private static string TryReadWindowsIdentityUserName ( )
789+
790+ /// <returns>
791+ /// On Windows: UserName in case of success, empty string for unexpected null in identity or Name
792+ /// <para/>
793+ /// On other OSes: null
794+ /// </returns>
795+ /// <exception cref="PlatformNotSupportedException">Thrown on non-Windows platforms on net462</exception>
796+ private static string ? TryReadWindowsIdentityUserName ( )
781797 {
782- #if ! NET462_OR_GREATER
798+ // According to docs RuntimeInformation.IsOSPlatform is supported from netstandard1.1,
799+ // but it's erroring in runtime on < net471
800+ #if NET471_OR_GREATER || NETSTANDARD2_0_OR_GREATER
783801 if ( ! RuntimeInformation . IsOSPlatform ( OSPlatform . Windows ) )
784802 {
785- return string . Empty ;
803+ return null ;
786804 }
787805#endif
788806 using var identity = WindowsIdentity . GetCurrent ( ) ;
0 commit comments