Delete NetEventSource.Enter/Exit events (#38874)
authorStephen Toub <stoub@microsoft.com>
Fri, 10 Jul 2020 13:31:21 +0000 (09:31 -0400)
committerGitHub <noreply@github.com>
Fri, 10 Jul 2020 13:31:21 +0000 (09:31 -0400)
They're super verbose, very inconsistent, costly, and not helpful (they appear to be trying to provide tracing of the full flow of calls, but they fail to do even that).

60 files changed:
src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs
src/libraries/Common/src/Interop/Windows/SspiCli/SSPIWrapper.cs
src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs
src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs
src/libraries/Common/src/System/Net/Http/aspnetcore/Quic/Implementations/MsQuic/MsQuicConnection.cs
src/libraries/Common/src/System/Net/Http/aspnetcore/Quic/Implementations/MsQuic/MsQuicListener.cs
src/libraries/Common/src/System/Net/Http/aspnetcore/Quic/Implementations/MsQuic/MsQuicStream.cs
src/libraries/Common/src/System/Net/LazyAsyncResult.cs
src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs
src/libraries/Common/src/System/Net/NTAuthentication.Common.cs
src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs
src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNtlmAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs
src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs
src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs
src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs
src/libraries/System.Net.Primitives/src/System/Net/SocketException.Unix.cs
src/libraries/System.Net.Primitives/src/System/Net/SocketException.cs
src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs
src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs
src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs
src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs
src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs
src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs
src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs
src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs
src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs

index 2ab7933..ed6e282 100644 (file)
@@ -663,8 +663,6 @@ internal static partial class Interop
 
         private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex)
         {
-            if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(null); }
-
             string header = null;
 
             HTTP_KNOWN_HEADER* pKnownHeader = (&request->Headers.KnownHeaders) + headerIndex;
@@ -682,7 +680,6 @@ internal static partial class Interop
                 header = new string(pKnownHeader->pRawValue + fixup, 0, pKnownHeader->RawValueLength);
             }
 
-            if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(null, $"HttpApi::GetKnownHeader() return:{header}"); }
             return header;
         }
 
@@ -721,8 +718,6 @@ internal static partial class Interop
 
         internal static unsafe WebHeaderCollection GetHeaders(IntPtr memoryBlob, IntPtr originalAddress)
         {
-            NetEventSource.Enter(null);
-
             // Return value.
             WebHeaderCollection headerCollection = new WebHeaderCollection();
             byte* pMemoryBlob = (byte*)memoryBlob;
@@ -770,17 +765,11 @@ internal static partial class Interop
                 pKnownHeader++;
             }
 
-            NetEventSource.Exit(null);
             return headerCollection;
         }
 
         internal static unsafe uint GetChunks(IntPtr memoryBlob, IntPtr originalAddress, ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(null, $"HttpApi::GetChunks() memoryBlob:{memoryBlob}");
-            }
-
             // Return value.
             uint dataRead = 0;
             byte* pMemoryBlob = (byte*)memoryBlob;
@@ -828,17 +817,11 @@ internal static partial class Interop
                 dataChunkIndex = -1;
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Exit(null);
-            }
             return dataRead;
         }
 
         internal static unsafe HTTP_VERB GetKnownVerb(IntPtr memoryBlob, IntPtr originalAddress)
         {
-            NetEventSource.Enter(null);
-
             // Return value.
             HTTP_VERB verb = HTTP_VERB.HttpVerbUnknown;
 
@@ -848,14 +831,11 @@ internal static partial class Interop
                 verb = request->Verb;
             }
 
-            NetEventSource.Exit(null);
             return verb;
         }
 
         internal static unsafe IPEndPoint GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
             SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
             SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);
 
@@ -874,14 +854,11 @@ internal static partial class Interop
                 endpoint = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort).Create(v6address) as IPEndPoint;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
             return endpoint;
         }
 
         internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
             SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
             SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);
 
@@ -900,7 +877,6 @@ internal static partial class Interop
                 endpoint = s_ipv6Any.Create(v6address) as IPEndPoint;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
             return endpoint;
         }
 
index 5cc399c..7477241 100644 (file)
@@ -14,8 +14,6 @@ namespace System.Net
     {
         internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(ISSPIInterface secModule)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
             if (secModule.SecurityPackages == null)
             {
                 lock (secModule)
@@ -52,7 +50,6 @@ namespace System.Net
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
             return secModule.SecurityPackages;
         }
 
@@ -82,11 +79,7 @@ namespace System.Net
 
         public static SafeFreeCredentials AcquireDefaultCredential(ISSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(null, package);
-                NetEventSource.Log.AcquireDefaultCredential(package, intent);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AcquireDefaultCredential(package, intent);
 
             SafeFreeCredentials? outCredential = null;
             int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential);
@@ -117,11 +110,7 @@ namespace System.Net
 
         public static SafeFreeCredentials AcquireCredentialsHandle(ISSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCHANNEL_CRED scc)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(null, package);
-                NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc);
 
             SafeFreeCredentials? outCredential = null;
             int errorCode = secModule.AcquireCredentialsHandle(
@@ -136,7 +125,6 @@ namespace System.Net
                 throw new Win32Exception(errorCode);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, outCredential);
             return outCredential;
         }
 
@@ -355,24 +343,19 @@ namespace System.Net
 
         public static SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
-
             SafeFreeContextBufferChannelBinding result;
             int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);
             if (errorCode != 0)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
                 return null;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, result);
             return result;
         }
 
         public static bool QueryBlittableContextAttributes<T>(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, ref T attribute) where T : unmanaged
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
-
             Span<T> span =
 #if NETSTANDARD2_0
                 stackalloc T[1] { attribute };
@@ -392,19 +375,16 @@ namespace System.Net
             {
                 if (errorCode != 0)
                 {
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
                     return false;
                 }
 
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, attribute);
                 return true;
             }
         }
 
         public static bool QueryBlittableContextAttributes<T>(ISSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, Type safeHandleType, out SafeHandle? sspiHandle, ref T attribute) where T : unmanaged
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
-
             Span<T> span =
 #if NETSTANDARD2_0
                 stackalloc T[1] { attribute };
@@ -422,11 +402,10 @@ namespace System.Net
 
             if (errorCode != 0)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
                 return false;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, attribute);
             return true;
         }
 
@@ -436,7 +415,6 @@ namespace System.Net
                 contextAttribute == Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES ||
                 contextAttribute == Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, contextAttribute);
 
             Span<IntPtr> buffer = stackalloc IntPtr[1];
             int errorCode = secModule.QueryContextAttributes(
@@ -452,20 +430,18 @@ namespace System.Net
             {
                 if (errorCode != 0)
                 {
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
                     return null;
                 }
 
                 string? result = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, result);
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, result);
                 return result;
             }
         }
 
         public static SafeFreeCertContext? QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(ISSPIInterface secModule, SafeDeleteContext securityContext)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
             Span<IntPtr> buffer = stackalloc IntPtr[1];
             int errorCode = secModule.QueryContextAttributes(
                 securityContext,
@@ -477,19 +453,16 @@ namespace System.Net
             if (errorCode != 0)
             {
                 sspiHandle?.Dispose();
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
                 return null;
             }
 
             var result = (SafeFreeCertContext)sspiHandle!;
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, result);
             return result;
         }
 
         public static bool QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(ISSPIInterface secModule, SafeDeleteContext securityContext, ref Interop.SspiCli.SecPkgContext_IssuerListInfoEx ctx, out SafeHandle? sspiHandle)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
             Span<Interop.SspiCli.SecPkgContext_IssuerListInfoEx> buffer =
 #if NETSTANDARD2_0
                 stackalloc Interop.SspiCli.SecPkgContext_IssuerListInfoEx[1] { ctx };
@@ -508,11 +481,10 @@ namespace System.Net
 
             if (errorCode != 0)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"ERROR = {ErrorDescription(errorCode)}");
                 return false;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, ctx);
             return true;
         }
 
index beae491..b4f3eb5 100644 (file)
@@ -199,8 +199,6 @@ namespace System.Net.Security
             Interop.SspiCli.CredentialUse intent,
             out SafeFreeCredentials outCredential)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, package, intent);
-
             int errorCode = -1;
             long timeStamp;
 
@@ -262,12 +260,9 @@ namespace System.Net.Security
             ref Interop.SspiCli.SCHANNEL_CRED authdata,
             out SafeFreeCredentials outCredential)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, package, intent, authdata);
-
             int errorCode = -1;
             long timeStamp;
 
-
             // If there is a certificate, wrap it into an array.
             // Not threadsafe.
             IntPtr copiedPtr = authdata.paCred;
@@ -389,8 +384,6 @@ namespace System.Net.Security
             ref SecurityBuffer outSecBuffer,
             ref Interop.SspiCli.ContextFlags outFlags)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}");
-
             if (inCredentials == null)
             {
                 throw new ArgumentNullException(nameof(inCredentials));
@@ -514,7 +507,6 @@ namespace System.Net.Security
                 outFreeContextBuffer?.Dispose();
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
             return errorCode;
         }
 
@@ -621,8 +613,6 @@ namespace System.Net.Security
             ref SecurityBuffer outSecBuffer,
             ref Interop.SspiCli.ContextFlags outFlags)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}");
-
             if (inCredentials == null)
             {
                 throw new ArgumentNullException(nameof(inCredentials));
@@ -756,7 +746,6 @@ namespace System.Net.Security
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
             return errorCode;
         }
 
@@ -854,12 +843,7 @@ namespace System.Net.Security
             ref SafeDeleteSslContext? refContext,
             in SecurityBuffer inSecBuffer)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken");
-                NetEventSource.Info(null, $"    refContext       = {refContext}");
-                NetEventSource.Info(null, $"    inSecBuffer      = {inSecBuffer}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}");
 
             var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1);
             int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
@@ -906,7 +890,6 @@ namespace System.Net.Security
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}");
             return errorCode;
         }
 
@@ -914,12 +897,7 @@ namespace System.Net.Security
             ref SafeDeleteContext? refContext,
             in SecurityBuffer inSecBuffer)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(null);
-                NetEventSource.Info(null, $"    refContext       = {refContext}");
-                NetEventSource.Info(null, $"    inSecBuffer      = {inSecBuffer}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}");
 
             int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle;
 
@@ -968,7 +946,6 @@ namespace System.Net.Security
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}");
             return errorCode;
         }
     }
index 48a67e1..c7c062c 100644 (file)
@@ -29,14 +29,9 @@ namespace System.Net
     // Usage:
     // - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations
     //   at call sites should guard access like:
-    //       if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, refArg1, valueTypeArg2); // entering an instance method with a value type arg
     //       if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string
     // - Operations that have zero allocations / measurable computations at call sites can use a simpler pattern, calling methods like:
-    //       NetEventSource.Enter(this);                   // entering an instance method
     //       NetEventSource.Info(this, "literal string");  // arbitrary message with a literal string
-    //       NetEventSource.Enter(this, refArg1, regArg2); // entering an instance method with two reference type arguments
-    //       NetEventSource.Enter(null);                   // entering a static method
-    //       NetEventSource.Enter(null, refArg1);          // entering a static method with one reference type argument
     //   Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
     //   However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere.
     // - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
@@ -103,7 +98,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+            if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
         }
 
         /// <summary>Logs entrance to a method.</summary>
@@ -115,7 +110,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(arg0);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
+            if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
         }
 
         /// <summary>Logs entrance to a method.</summary>
@@ -129,7 +124,7 @@ namespace System.Net
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(arg0);
             DebugValidateArg(arg1);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
+            if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
         }
 
         /// <summary>Logs entrance to a method.</summary>
@@ -145,7 +140,7 @@ namespace System.Net
             DebugValidateArg(arg0);
             DebugValidateArg(arg1);
             DebugValidateArg(arg2);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
+            if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
         }
 
         [Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
@@ -163,7 +158,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+            if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
         }
 
         /// <summary>Logs exit from a method.</summary>
@@ -175,7 +170,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(arg0);
-            if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
+            if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
         }
 
         /// <summary>Logs exit from a method.</summary>
@@ -189,7 +184,7 @@ namespace System.Net
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(arg0);
             DebugValidateArg(arg1);
-            if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
+            if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
         }
 
         [Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
@@ -207,7 +202,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+            if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
         }
 
         /// <summary>Logs an information message.</summary>
@@ -219,7 +214,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(message);
-            if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
         }
 
         [Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
@@ -237,7 +232,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+            if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
         }
 
         /// <summary>Logs an error message.</summary>
@@ -249,7 +244,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(message);
-            if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
         }
 
         [Event(ErrorEventId, Level = EventLevel.Error, Keywords = Keywords.Default)]
@@ -268,7 +263,7 @@ namespace System.Net
             // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
             // that should never happen in production, and thus we don't care about extra costs.
 
-            if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
+            if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
             Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
         }
 
@@ -282,7 +277,7 @@ namespace System.Net
             // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
             // that should never happen in production, and thus we don't care about extra costs.
 
-            if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
             Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
         }
 
@@ -311,7 +306,7 @@ namespace System.Net
         [NonEvent]
         public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null)
         {
-            if (Log.IsEnabled())
+            if (IsEnabled)
             {
                 if (offset < 0 || offset > buffer.Length - count)
                 {
@@ -343,7 +338,7 @@ namespace System.Net
             Debug.Assert(bufferPtr != IntPtr.Zero);
             Debug.Assert(count >= 0);
 
-            if (Log.IsEnabled())
+            if (IsEnabled)
             {
                 var buffer = new byte[Math.Min(count, MaxDumpSize)];
                 fixed (byte* targetPtr = buffer)
@@ -369,7 +364,7 @@ namespace System.Net
         {
             DebugValidateArg(first);
             DebugValidateArg(second);
-            if (Log.IsEnabled()) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
+            if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
         }
 
         /// <summary>Logs a relationship between two objects.</summary>
@@ -383,7 +378,7 @@ namespace System.Net
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(first);
             DebugValidateArg(second);
-            if (Log.IsEnabled()) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
+            if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
         }
 
         [Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
@@ -396,7 +391,7 @@ namespace System.Net
         [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
         private static void DebugValidateArg(object? arg)
         {
-            if (!Log.IsEnabled())
+            if (!IsEnabled)
             {
                 Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check");
                 Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
@@ -406,9 +401,12 @@ namespace System.Net
         [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
         private static void DebugValidateArg(FormattableString? arg)
         {
-            Debug.Assert(Log.IsEnabled() || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
+            Debug.Assert(IsEnabled || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
         }
 
+        public static new bool IsEnabled =>
+            Log.IsEnabled();
+
         [NonEvent]
         public static string IdOf(object? value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
 
index 4fe3289..0046c56 100644 (file)
@@ -51,21 +51,17 @@ namespace System.Net.Quic.Implementations.MsQuic
         // constructor for inbound connections
         public MsQuicConnection(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, IntPtr nativeObjPtr)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             _localEndPoint = localEndPoint;
             _remoteEndPoint = remoteEndPoint;
             _ptr = nativeObjPtr;
 
             SetCallbackHandler();
             SetIdleTimeout(TimeSpan.FromSeconds(120));
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // constructor for outbound connections
         public MsQuicConnection(QuicClientConnectionOptions options)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             // TODO need to figure out if/how we want to expose sessions
             // Creating a session per connection isn't ideal.
             _session = new MsQuicSession();
@@ -74,8 +70,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
             SetCallbackHandler();
             SetIdleTimeout(options.IdleTimeout);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal override IPEndPoint LocalEndPoint
@@ -168,8 +162,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         private uint HandleEventConnected(ConnectionEvent connectionEvent)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             SOCKADDR_INET inetAddress = MsQuicParameterHelpers.GetINetParam(MsQuicApi.Api, _ptr, (uint)QUIC_PARAM_LEVEL.CONNECTION, (uint)QUIC_PARAM_CONN.LOCAL_ADDRESS);
             _localEndPoint = MsQuicAddressHelpers.INetToIPEndPoint(inetAddress);
 
@@ -179,14 +171,11 @@ namespace System.Net.Quic.Implementations.MsQuic
             // handle event shutdown initiated by transport
             _connectTcs.Complete(MsQuicStatusCodes.Success);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventShutdownInitiatedByTransport(ConnectionEvent connectionEvent)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (!_connected)
             {
                 _connectTcs.CompleteException(new IOException("Connection has been shutdown."));
@@ -194,7 +183,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
             _acceptQueue.Writer.Complete();
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
 
             return MsQuicStatusCodes.Success;
         }
@@ -208,23 +196,14 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         private uint HandleEventShutdownComplete(ConnectionEvent connectionEvent)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             _shutdownTcs.Complete(MsQuicStatusCodes.Success);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventNewStream(ConnectionEvent connectionEvent)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             MsQuicStream msQuicStream = new MsQuicStream(this, connectionEvent.StreamFlags, connectionEvent.Data.NewStream.Stream, inbound: true);
-
             _acceptQueue.Writer.TryWrite(msQuicStream);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
@@ -235,8 +214,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         internal override async ValueTask<QuicStreamProvider> AcceptStreamAsync(CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             MsQuicStream stream;
@@ -254,7 +231,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 };
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return stream;
         }
 
@@ -305,8 +281,6 @@ namespace System.Net.Quic.Implementations.MsQuic
         private MsQuicStream StreamOpen(
             QUIC_STREAM_OPEN_FLAG flags)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             IntPtr streamPtr = IntPtr.Zero;
             QuicExceptionHelpers.ThrowIfFailed(
                 MsQuicApi.Api.StreamOpenDelegate(
@@ -317,10 +291,7 @@ namespace System.Net.Quic.Implementations.MsQuic
                 out streamPtr),
                 "Failed to open stream to peer.");
 
-            MsQuicStream stream = new MsQuicStream(this, flags, streamPtr, inbound: false);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return stream;
+            return new MsQuicStream(this, flags, streamPtr, inbound: false);
         }
 
         private void SetCallbackHandler()
@@ -337,15 +308,12 @@ namespace System.Net.Quic.Implementations.MsQuic
             QUIC_CONNECTION_SHUTDOWN_FLAG Flags,
             long ErrorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             uint status = MsQuicApi.Api.ConnectionShutdownDelegate(
                 _ptr,
                 (uint)Flags,
                 ErrorCode);
             QuicExceptionHelpers.ThrowIfFailed(status, "Failed to shutdown connection.");
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return _shutdownTcs.GetTypelessValueTask();
         }
 
@@ -377,8 +345,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 return;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (_ptr != IntPtr.Zero)
             {
                 MsQuicApi.Api.ConnectionCloseDelegate?.Invoke(_ptr);
@@ -394,8 +360,6 @@ namespace System.Net.Quic.Implementations.MsQuic
             }
 
             _disposed = true;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal override ValueTask CloseAsync(long errorCode, CancellationToken cancellationToken = default)
index 0a9b004..c8d3388 100644 (file)
@@ -62,8 +62,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         internal override async ValueTask<QuicConnectionProvider> AcceptConnectionAsync(CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             MsQuicConnection connection;
@@ -81,7 +79,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _options.CertificateFilePath,
                 _options.PrivateKeyFilePath).ConfigureAwait(false);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return connection;
         }
 
index 085abfd..6b8e9ce 100644 (file)
@@ -124,8 +124,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         internal override async ValueTask WriteAsync(ReadOnlySequence<byte> buffers, bool endStream, CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             using CancellationTokenRegistration registration = await HandleWriteStartState(cancellationToken).ConfigureAwait(false);
@@ -133,8 +131,6 @@ namespace System.Net.Quic.Implementations.MsQuic
             await SendReadOnlySequenceAsync(buffers, endStream ? QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE).ConfigureAwait(false);
 
             HandleWriteCompletedState();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal override ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, CancellationToken cancellationToken = default)
@@ -144,8 +140,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         internal override async ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, bool endStream, CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             using CancellationTokenRegistration registration = await HandleWriteStartState(cancellationToken).ConfigureAwait(false);
@@ -153,14 +147,10 @@ namespace System.Net.Quic.Implementations.MsQuic
             await SendReadOnlyMemoryListAsync(buffers, endStream ? QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE).ConfigureAwait(false);
 
             HandleWriteCompletedState();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, bool endStream, CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             using CancellationTokenRegistration registration = await HandleWriteStartState(cancellationToken).ConfigureAwait(false);
@@ -168,8 +158,6 @@ namespace System.Net.Quic.Implementations.MsQuic
             await SendReadOnlyMemoryAsync(buffer, endStream ? QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE).ConfigureAwait(false);
 
             HandleWriteCompletedState();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private async ValueTask<CancellationTokenRegistration> HandleWriteStartState(CancellationToken cancellationToken)
@@ -228,8 +216,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         internal override async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             if (!_canRead)
@@ -241,7 +227,6 @@ namespace System.Net.Quic.Implementations.MsQuic
             {
                 if (_readState == ReadState.ReadsCompleted)
                 {
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                     return 0;
                 }
                 else if (_readState == ReadState.Aborted)
@@ -310,8 +295,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return actual;
         }
 
@@ -319,8 +302,6 @@ namespace System.Net.Quic.Implementations.MsQuic
         // If so, we need to complete the read here as well.
         internal override void AbortRead(long errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             lock (_sync)
@@ -330,13 +311,10 @@ namespace System.Net.Quic.Implementations.MsQuic
 
             MsQuicApi.Api.StreamShutdownDelegate(_ptr, (uint)QUIC_STREAM_SHUTDOWN_FLAG.ABORT_RECV, errorCode);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal override void AbortWrite(long errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             bool shouldComplete = false;
@@ -356,14 +334,10 @@ namespace System.Net.Quic.Implementations.MsQuic
             }
 
             MsQuicApi.Api.StreamShutdownDelegate(_ptr, (uint)QUIC_STREAM_SHUTDOWN_FLAG.ABORT_SEND, errorCode);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal override ValueTask ShutdownWriteCompleted(CancellationToken cancellationToken = default)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             // TODO do anything to stop writes?
@@ -385,8 +359,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 }
             });
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return _shutdownWriteResettableCompletionSource.GetTypelessValueTask();
         }
 
@@ -434,8 +406,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 return default;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             CleanupSendState();
 
             if (_ptr != IntPtr.Zero)
@@ -448,7 +418,6 @@ namespace System.Net.Quic.Implementations.MsQuic
             _handle.Free();
 
             _disposed = true;
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
 
             return default;
         }
@@ -471,8 +440,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 return;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             CleanupSendState();
 
             if (_ptr != IntPtr.Zero)
@@ -484,8 +451,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
             _handle.Free();
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             _disposed = true;
         }
 
@@ -577,8 +542,6 @@ namespace System.Net.Quic.Implementations.MsQuic
 
         private unsafe uint HandleEventRecv(ref MsQuicNativeMethods.StreamEvent evt)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             StreamEventDataRecv receieveEvent = evt.Data.Recv;
             for (int i = 0; i < receieveEvent.BufferCount; i++)
             {
@@ -600,15 +563,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _receiveResettableCompletionSource.Complete((uint)receieveEvent.TotalBufferLength);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Pending;
         }
 
         private uint HandleEventPeerRecvAborted(ref StreamEvent evt)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             bool shouldComplete = false;
             lock (_sync)
             {
@@ -625,15 +584,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _sendResettableCompletionSource.CompleteException(new QuicStreamAbortedException(_sendErrorCode));
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleStartComplete()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             bool shouldComplete = false;
             lock (_sync)
             {
@@ -649,14 +604,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _sendResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventSendShutdownComplete(ref MsQuicNativeMethods.StreamEvent evt)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             bool shouldComplete = false;
             lock (_sync)
             {
@@ -672,15 +624,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _shutdownWriteResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventShutdownComplete()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             bool shouldReadComplete = false;
             bool shouldShutdownWriteComplete = false;
 
@@ -713,15 +661,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _shutdownWriteResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventPeerSendAborted(ref StreamEvent evt)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             bool shouldComplete = false;
             lock (_sync)
             {
@@ -738,15 +682,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _receiveResettableCompletionSource.CompleteException(new QuicStreamAbortedException(_readErrorCode));
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventPeerSendShutdown()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             bool shouldComplete = false;
 
             lock (_sync)
@@ -767,15 +707,11 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _receiveResettableCompletionSource.Complete(0);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
         private uint HandleEventSendComplete(ref StreamEvent evt)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             CleanupSendState();
 
             // TODO throw if a write was canceled.
@@ -796,8 +732,6 @@ namespace System.Net.Quic.Implementations.MsQuic
                 _sendResettableCompletionSource.Complete(MsQuicStatusCodes.Success);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return MsQuicStatusCodes.Success;
         }
 
index bbde411..b31e995 100644 (file)
@@ -106,8 +106,6 @@ namespace System.Net
         {
             get
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
 #if DEBUG
                 // Can't be called when state is protected.
                 if (_protectState)
@@ -135,7 +133,6 @@ namespace System.Net
                     LazilyCreateEvent(out asyncEvent);
                 }
 
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncEvent);
                 return asyncEvent;
             }
         }
@@ -191,8 +188,6 @@ namespace System.Net
         {
             get
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
 #if DEBUG
                 // Can't be called when state is protected.
                 if (_protectState)
@@ -208,7 +203,6 @@ namespace System.Net
                     result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
                 }
 
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result > 0);
                 return result > 0;
             }
         }
@@ -218,8 +212,6 @@ namespace System.Net
         {
             get
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
 #if DEBUG
                 // Can't be called when state is protected.
                 if (_protectState)
@@ -309,8 +301,6 @@ namespace System.Net
         // the equivalent of InvokeCallback().
         protected void ProtectedInvokeCallback(object? result, IntPtr userToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, result, userToken);
-
             // Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion.
             if (result == DBNull.Value)
             {
@@ -494,7 +484,6 @@ namespace System.Net
                 sw.SpinOnce();
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, _result);
             return _result;
         }
 
index c308c07..f55fedc 100644 (file)
@@ -30,14 +30,9 @@ namespace System.Net
     // Usage:
     // - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations
     //   at call sites should guard access like:
-    //       if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, refArg1, valueTypeArg2); // entering an instance method with a value type arg
     //       if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string
     // - Operations that have zero allocations / measurable computations at call sites can use a simpler pattern, calling methods like:
-    //       NetEventSource.Enter(this);                   // entering an instance method
     //       NetEventSource.Info(this, "literal string");  // arbitrary message with a literal string
-    //       NetEventSource.Enter(this, refArg1, regArg2); // entering an instance method with two reference type arguments
-    //       NetEventSource.Enter(null);                   // entering a static method
-    //       NetEventSource.Enter(null, refArg1);          // entering a static method with one reference type argument
     //   Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
     //   However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere.
     // - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
@@ -61,7 +56,9 @@ namespace System.Net
         {
             public const EventKeywords Default = (EventKeywords)0x0001;
             public const EventKeywords Debug = (EventKeywords)0x0002;
-            public const EventKeywords EnterExit = (EventKeywords)0x0004;
+
+            // No longer used:
+            // EnterExit = (EventKeywords)0x0004;
         }
 
         private const string MissingMember = "(?)";
@@ -70,8 +67,10 @@ namespace System.Net
         private const string NoParameters = "";
         private const int MaxDumpSize = 1024;
 
-        private const int EnterEventId = 1;
-        private const int ExitEventId = 2;
+        // No longer used:
+        // EnterEventId = 1;
+        // ExitEventId = 2;
+
         private const int AssociateEventId = 3;
         private const int InfoEventId = 4;
         private const int ErrorEventId = 5;
@@ -94,110 +93,6 @@ namespace System.Net
         #endregion
 
         #region Events
-        #region Enter
-        /// <summary>Logs entrance to a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="formattableString">A description of the entrance, including any arguments to the call.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Enter(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
-        }
-
-        /// <summary>Logs entrance to a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="arg0">The object to log.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Enter(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(arg0);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
-        }
-
-        /// <summary>Logs entrance to a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="arg0">The first object to log.</param>
-        /// <param name="arg1">The second object to log.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Enter(object? thisOrContextObject, object? arg0, object? arg1, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(arg0);
-            DebugValidateArg(arg1);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
-        }
-
-        /// <summary>Logs entrance to a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="arg0">The first object to log.</param>
-        /// <param name="arg1">The second object to log.</param>
-        /// <param name="arg2">The third object to log.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Enter(object? thisOrContextObject, object? arg0, object? arg1, object? arg2, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(arg0);
-            DebugValidateArg(arg1);
-            DebugValidateArg(arg2);
-            if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
-        }
-
-        [Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
-        private void Enter(string thisOrContextObject, string? memberName, string parameters) =>
-            WriteEvent(EnterEventId, thisOrContextObject, memberName ?? MissingMember, parameters);
-        #endregion
-
-        #region Exit
-        /// <summary>Logs exit from a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="formattableString">A description of the exit operation, including any return values.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Exit(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
-        }
-
-        /// <summary>Logs exit from a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="arg0">A return value from the member.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Exit(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(arg0);
-            if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
-        }
-
-        /// <summary>Logs exit from a method.</summary>
-        /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
-        /// <param name="arg0">A return value from the member.</param>
-        /// <param name="arg1">A second return value from the member.</param>
-        /// <param name="memberName">The calling member.</param>
-        [NonEvent]
-        public static void Exit(object? thisOrContextObject, object? arg0, object? arg1, [CallerMemberName] string? memberName = null)
-        {
-            DebugValidateArg(thisOrContextObject);
-            DebugValidateArg(arg0);
-            DebugValidateArg(arg1);
-            if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
-        }
-
-        [Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
-        private void Exit(string thisOrContextObject, string? memberName, string? result) =>
-            WriteEvent(ExitEventId, thisOrContextObject, memberName ?? MissingMember, result);
-        #endregion
-
         #region Info
         /// <summary>Logs an information message.</summary>
         /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
@@ -208,7 +103,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+            if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
         }
 
         /// <summary>Logs an information message.</summary>
@@ -220,7 +115,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(message);
-            if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
         }
 
         [Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
@@ -238,7 +133,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+            if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
         }
 
         /// <summary>Logs an error message.</summary>
@@ -250,7 +145,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(message);
-            if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
         }
 
         [Event(ErrorEventId, Level = EventLevel.Error, Keywords = Keywords.Default)]
@@ -272,7 +167,7 @@ namespace System.Net
             // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
             // that should never happen in production, and thus we don't care about extra costs.
 
-            if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
+            if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
             Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
         }
 
@@ -289,7 +184,7 @@ namespace System.Net
             // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
             // that should never happen in production, and thus we don't care about extra costs.
 
-            if (Log.IsEnabled()) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
             Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
         }
 
@@ -308,7 +203,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(formattableString);
-            if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+            if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
         }
 
         /// <summary>Logs an info at verbose mode.</summary>
@@ -320,7 +215,7 @@ namespace System.Net
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(message);
-            if (Log.IsEnabled()) Log.VerboseMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+            if (IsEnabled) Log.VerboseMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
         }
 
         [Event(ErrorEventId, Level = EventLevel.Verbose, Keywords = Keywords.Default)]
@@ -348,7 +243,7 @@ namespace System.Net
         [NonEvent]
         public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null)
         {
-            if (Log.IsEnabled())
+            if (IsEnabled)
             {
                 if (offset < 0 || offset > buffer.Length - count)
                 {
@@ -380,7 +275,7 @@ namespace System.Net
             Debug.Assert(bufferPtr != IntPtr.Zero);
             Debug.Assert(count >= 0);
 
-            if (Log.IsEnabled())
+            if (IsEnabled)
             {
                 var buffer = new byte[Math.Min(count, MaxDumpSize)];
                 fixed (byte* targetPtr = buffer)
@@ -406,7 +301,7 @@ namespace System.Net
         {
             DebugValidateArg(first);
             DebugValidateArg(second);
-            if (Log.IsEnabled()) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
+            if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
         }
 
         /// <summary>Logs a relationship between two objects.</summary>
@@ -420,7 +315,7 @@ namespace System.Net
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(first);
             DebugValidateArg(second);
-            if (Log.IsEnabled()) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
+            if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
         }
 
         [Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
@@ -433,7 +328,7 @@ namespace System.Net
         [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
         private static void DebugValidateArg(object? arg)
         {
-            if (!Log.IsEnabled())
+            if (!IsEnabled)
             {
                 Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check");
                 Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
@@ -443,9 +338,12 @@ namespace System.Net
         [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
         private static void DebugValidateArg(FormattableString? arg)
         {
-            Debug.Assert(Log.IsEnabled() || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
+            Debug.Assert(IsEnabled || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
         }
 
+        public static new bool IsEnabled =>
+            Log.IsEnabled();
+
         [NonEvent]
         public static string IdOf(object? value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
 
index 4ce0a91..5e58089 100644 (file)
@@ -100,7 +100,7 @@ namespace System.Net
         [MemberNotNull(nameof(_package))]
         private void Initialize(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, package, spn, requestedContextFlags);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"package={package}, spn={spn}, requestedContextFlags={requestedContextFlags}");
 
             _tokenSize = NegotiateStreamPal.QueryMaxTokenSize(package);
             _isServer = isServer;
@@ -212,8 +212,6 @@ namespace System.Net
         // Accepts an incoming binary security blob and returns an outgoing binary security blob.
         internal byte[]? GetOutgoingBlob(byte[]? incomingBlob, bool throwOnError, out SecurityStatusPal statusCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, incomingBlob);
-
             byte[]? result = new byte[_tokenSize];
 
             bool firstTime = _securityContext == null;
@@ -279,12 +277,9 @@ namespace System.Net
                 _isCompleted = true;
                 if (throwOnError)
                 {
-                    Exception exception = NegotiateStreamPal.CreateExceptionFromError(statusCode);
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, exception);
-                    throw exception;
+                    throw NegotiateStreamPal.CreateExceptionFromError(statusCode);
                 }
 
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"null statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode})");
                 return null;
             }
             else if (firstTime && _credentialsHandle != null)
@@ -300,17 +295,12 @@ namespace System.Net
                 // Success.
                 _isCompleted = true;
             }
-            else if (NetEventSource.Log.IsEnabled())
+            else
             {
                 // We need to continue.
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"need continue statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode}) _securityContext:{_securityContext}");
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"IsCompleted: {IsCompleted}");
-            }
-
             return result;
         }
 
index 9f1d078..9108854 100644 (file)
@@ -308,7 +308,6 @@ namespace System.Net.Http
         // a pending operation, it would cause random failures in the other threads when we expect a valid handle.
         private void CancelPendingResponseStreamReadOperation()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             lock (_state.Lock)
             {
                 if (_state.AsyncReadInProgress)
@@ -318,8 +317,6 @@ namespace System.Net.Http
                     if (NetEventSource.Log.IsEnabled()) NetEventSource.Info("after dispose");
                 }
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
     }
 }
index 9770b3a..a08edaf 100644 (file)
@@ -645,16 +645,12 @@ namespace System.Net.Http
         public void CancelPendingRequests()
         {
             CheckDisposed();
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
 
             // With every request we link this cancellation token source.
-            CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
-                new CancellationTokenSource());
+            CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts, new CancellationTokenSource());
 
             currentCts.Cancel();
             currentCts.Dispose();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         #endregion Advanced Send Overloads
index 1d8ab4f..0ec9f1a 100644 (file)
@@ -143,12 +143,10 @@ namespace System.Net.Http
         protected HttpContent()
         {
             // Log to get an ID for the current content. This ID is used when the content gets associated to a message.
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this);
 
             // We start with the assumption that we can calculate the content length.
             _canCalculateLength = true;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public Task<string> ReadAsStringAsync() =>
index c71a110..60e39a2 100644 (file)
@@ -21,8 +21,6 @@ namespace System.Net.Http
 
         public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, handler);
-
             if (handler == null)
             {
                 throw new ArgumentNullException(nameof(handler));
@@ -32,8 +30,6 @@ namespace System.Net.Http
 
             _handler = handler;
             _disposeHandler = disposeHandler;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public virtual HttpResponseMessage Send(HttpRequestMessage request,
@@ -45,13 +41,7 @@ namespace System.Net.Http
             }
             CheckDisposed();
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, request);
-
-            HttpResponseMessage response = _handler.Send(request, cancellationToken);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, response);
-
-            return response;
+            return _handler.Send(request, cancellationToken);
         }
 
         public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
@@ -63,13 +53,7 @@ namespace System.Net.Http
             }
             CheckDisposed();
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, request);
-
-            Task<HttpResponseMessage> task = _handler.SendAsync(request, cancellationToken);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, task);
-
-            return task;
+            return _handler.SendAsync(request, cancellationToken);
         }
 
         public void Dispose()
index 0bd6044..3cbb1d0 100644 (file)
@@ -130,15 +130,11 @@ namespace System.Net.Http
 
         public HttpRequestMessage(HttpMethod method, Uri? requestUri)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, method, requestUri);
             InitializeValues(method, requestUri);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public HttpRequestMessage(HttpMethod method, string? requestUri)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, method, requestUri);
-
             // It's OK to have a 'null' request Uri. If HttpClient is used, the 'BaseAddress' will be added.
             // If there is no 'BaseAddress', sending this request message will throw.
             // Note that we also allow the string to be empty: null and empty are considered equivalent.
@@ -150,8 +146,6 @@ namespace System.Net.Http
             {
                 InitializeValues(method, new Uri(requestUri, UriKind.RelativeOrAbsolute));
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public override string ToString()
index dabe637..dafe058 100644 (file)
@@ -154,8 +154,6 @@ namespace System.Net.Http
 
         public HttpResponseMessage(HttpStatusCode statusCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, statusCode);
-
             if (((int)statusCode < 0) || ((int)statusCode > 999))
             {
                 throw new ArgumentOutOfRangeException(nameof(statusCode));
@@ -163,8 +161,6 @@ namespace System.Net.Http
 
             _statusCode = statusCode;
             _version = HttpUtilities.DefaultResponseVersion;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public HttpResponseMessage EnsureSuccessStatusCode()
index 487847d..e01950e 100644 (file)
@@ -482,8 +482,6 @@ namespace System.Net.Http
         /// <summary>Removes unusable connections from each pool, and removes stale pools entirely.</summary>
         private void RemoveStalePools()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             Debug.Assert(_cleaningTimer != null);
 
             // Iterate through each pool in the set of pools.  For each, ask it to clear out
@@ -517,8 +515,6 @@ namespace System.Net.Http
             // than reused.  This should be a rare occurrence, so for now we don't worry about it.  In the
             // future, there are a variety of possible ways to address it, such as allowing connections to
             // be returned to pools they weren't associated with.
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private static string GetIdentityIfDefaultCredentialsUsed(bool defaultCredentialsUsed)
index fb4bc80..cf16936 100644 (file)
@@ -27,8 +27,6 @@ namespace System.Net.Http
 
         internal override async ValueTask<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, request, cancellationToken);
-
             HttpResponseMessage response = await _initialInnerHandler.SendAsync(request, async, cancellationToken).ConfigureAwait(false);
 
             uint redirectCount = 0;
@@ -81,8 +79,6 @@ namespace System.Net.Http
                 response = await _redirectInnerHandler.SendAsync(request, async, cancellationToken).ConfigureAwait(false);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
             return response;
         }
 
index b100e04..bde2c4e 100644 (file)
@@ -29,8 +29,6 @@ namespace System.Net
 
         public HttpListener()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             _state = State.Stopped;
             _internalLock = new object();
             _defaultServiceNames = new ServiceNameStore();
@@ -41,8 +39,6 @@ namespace System.Net
             // default: no CBT checks on any platform (appcompat reasons); applies also to PolicyEnforcement
             // config element
             _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate
@@ -105,16 +101,13 @@ namespace System.Net
         {
             get
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
                 CheckDisposed();
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
                 return _prefixes;
             }
         }
 
         internal void AddPrefix(string uriPrefix)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"uriPrefix:{uriPrefix}");
             string registeredPrefix = null;
             try
             {
@@ -192,17 +185,12 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"prefix: {registeredPrefix}");
-            }
         }
 
         internal bool ContainsPrefix(string uriPrefix) => _uriPrefixes.Contains(uriPrefix);
 
         internal bool RemovePrefix(string uriPrefix)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"uriPrefix: {uriPrefix}");
             try
             {
                 CheckDisposed();
@@ -230,41 +218,29 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, $"uriPrefix: {uriPrefix}");
-            }
             return true;
         }
 
         internal void RemoveAll(bool clear)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-            try
+            CheckDisposed();
+            // go through the uri list and unregister for each one of them
+            if (_uriPrefixes.Count > 0)
             {
-                CheckDisposed();
-                // go through the uri list and unregister for each one of them
-                if (_uriPrefixes.Count > 0)
+                if (_state == State.Started)
                 {
-                    if (_state == State.Started)
+                    foreach (string registeredPrefix in _uriPrefixes.Values)
                     {
-                        foreach (string registeredPrefix in _uriPrefixes.Values)
-                        {
-                            RemovePrefixCore(registeredPrefix);
-                        }
+                        RemovePrefixCore(registeredPrefix);
                     }
+                }
 
-                    if (clear)
-                    {
-                        _uriPrefixes.Clear();
-                        _defaultServiceNames.Clear();
-                    }
+                if (clear)
+                {
+                    _uriPrefixes.Clear();
+                    _defaultServiceNames.Clear();
                 }
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
         public string Realm
@@ -299,7 +275,6 @@ namespace System.Net
 
         public void Close()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, nameof(Close));
             try
             {
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info("HttpListenerRequest::Close()");
@@ -310,10 +285,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Close {exception}");
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
         internal void CheckDisposed()
index bab1e5b..6a64481 100644 (file)
@@ -231,22 +231,15 @@ namespace System.Net
 
         public X509Certificate2 GetClientCertificate()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-            try
-            {
-                if (ClientCertState == ListenerClientCertState.InProgress)
-                    throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()"));
-                ClientCertState = ListenerClientCertState.InProgress;
+            if (ClientCertState == ListenerClientCertState.InProgress)
+                throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()"));
+            ClientCertState = ListenerClientCertState.InProgress;
 
-                GetClientCertificateCore();
+            GetClientCertificateCore();
+
+            ClientCertState = ListenerClientCertState.Completed;
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
 
-                ClientCertState = ListenerClientCertState.Completed;
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
-            }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
             return ClientCertificate;
         }
 
index f0bab3d..c05875a 100644 (file)
@@ -15,11 +15,8 @@ namespace System.Net
 
         public override int Read(byte[] buffer, int offset, int size)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
+
             if (buffer == null)
             {
                 throw new ArgumentNullException(nameof(buffer));
@@ -34,8 +31,6 @@ namespace System.Net
             }
             if (size == 0 || _closed)
             {
-                if (NetEventSource.Log.IsEnabled())
-                    NetEventSource.Exit(this, "dataRead:0");
                 return 0;
             }
 
@@ -44,11 +39,8 @@ namespace System.Net
 
         public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
+
             if (buffer == null)
             {
                 throw new ArgumentNullException(nameof(buffer));
@@ -93,17 +85,10 @@ namespace System.Net
 
         protected override void Dispose(bool disposing)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, "_closed:" + _closed);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_closed:" + _closed);
 
             _closed = true;
             base.Dispose(disposing);
-
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this);
         }
     }
 }
index 8e62391..fea4e19 100644 (file)
@@ -42,11 +42,8 @@ namespace System.Net
 
         public override void Write(byte[] buffer, int offset, int size)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset);
+
             if (buffer == null)
             {
                 throw new ArgumentNullException(nameof(buffer));
@@ -61,7 +58,6 @@ namespace System.Net
             }
             if (_closed)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 return;
             }
 
@@ -89,11 +85,8 @@ namespace System.Net
 
         public override void EndWrite(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"asyncResult:{asyncResult}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
+
             if (asyncResult == null)
             {
                 throw new ArgumentNullException(nameof(asyncResult));
@@ -104,7 +97,6 @@ namespace System.Net
 
         protected override void Dispose(bool disposing)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 if (disposing)
@@ -112,7 +104,6 @@ namespace System.Net
                     if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_closed:" + _closed);
                     if (_closed)
                     {
-                        if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                         return;
                     }
                     _closed = true;
@@ -123,7 +114,6 @@ namespace System.Net
             {
                 base.Dispose(disposing);
             }
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
     }
 }
index 87d2dc6..02a747e 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Net
 
         public void Start()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             lock (_internalLock)
             {
                 try
@@ -52,10 +51,6 @@ namespace System.Net
                     if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Start {exception}");
                     throw;
                 }
-                finally
-                {
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-                }
             }
         }
 
@@ -72,7 +67,6 @@ namespace System.Net
 
         public void Stop()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
 
             lock (_internalLock)
             {
@@ -94,14 +88,12 @@ namespace System.Net
                 finally
                 {
                     _state = State.Stopped;
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 }
             }
         }
 
         public void Abort()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
 
             lock (_internalLock)
             {
@@ -126,14 +118,12 @@ namespace System.Net
                 finally
                 {
                     _state = State.Closed;
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 }
             }
         }
 
         private void Dispose()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
 
             lock (_internalLock)
             {
@@ -154,7 +144,6 @@ namespace System.Net
                 finally
                 {
                     _state = State.Closed;
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 }
             }
         }
index 33f9e1c..d92f436 100644 (file)
@@ -220,8 +220,6 @@ namespace System.Net
 
         public void Start()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             // Make sure there are no race conditions between Start/Stop/Abort/Close/Dispose and
             // calls to SetupV2Config: Start needs to setup all resources (esp. in V2 where besides
             // the request handle, there is also a server session and a Url group. Abort/Stop must
@@ -269,10 +267,6 @@ namespace System.Net
                     if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Start {exception}");
                     throw;
                 }
-                finally
-                {
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-                }
             }
         }
 
@@ -355,7 +349,6 @@ namespace System.Net
 
         public void Stop()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 lock (_internalLock)
@@ -383,10 +376,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"Stop {exception}");
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
         private unsafe void CreateRequestQueueHandle()
@@ -407,8 +396,6 @@ namespace System.Net
 
         public void Abort()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             lock (_internalLock)
             {
                 try
@@ -435,15 +422,12 @@ namespace System.Net
                 finally
                 {
                     _state = State.Closed;
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 }
             }
         }
 
         private void Dispose()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             lock (_internalLock)
             {
                 try
@@ -464,7 +448,6 @@ namespace System.Net
                 finally
                 {
                     _state = State.Closed;
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 }
             }
         }
@@ -506,8 +489,6 @@ namespace System.Net
 
         public HttpListenerContext GetContext()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             SyncRequestContext memoryBlob = null;
             HttpListenerContext httpContext = null;
             bool stoleBlob = false;
@@ -612,7 +593,6 @@ namespace System.Net
                     memoryBlob.ReleasePins();
                     memoryBlob.Close();
                 }
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "RequestTraceIdentifier: " + (httpContext != null ? httpContext.Request.RequestTraceIdentifier.ToString() : "<null>"));
             }
         }
 
@@ -629,7 +609,6 @@ namespace System.Net
 
         public IAsyncResult BeginGetContext(AsyncCallback callback, object state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ListenerAsyncResult asyncResult = null;
             try
             {
@@ -656,17 +635,12 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"BeginGetContext {exception}");
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
 
             return asyncResult;
         }
 
         public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             HttpListenerContext httpContext = null;
             try
             {
@@ -697,10 +671,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"EndGetContext {exception}");
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "EndGetContext " + httpContext == null ? "<no context>" : "HttpListenerContext" + httpContext.ToString() + " RequestTraceIdentifier#" + httpContext.Request.RequestTraceIdentifier);
-            }
             return httpContext;
         }
 
@@ -1741,8 +1711,6 @@ namespace System.Net
 
         internal static ChannelBinding GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(session.Listener, $"connectionId: {connectionId}");
-
             // +128 since a CBT is usually <128 thus we need to call HRCC just once. If the CBT
             // is >128 we will get ERROR_MORE_DATA and call again
             int size = sizeof(Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS) + 128;
index a296fcc..e2bb4b9 100644 (file)
@@ -76,8 +76,6 @@ namespace System.Net
 
         internal void Close()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             try
             {
                 _response?.Close();
@@ -101,12 +99,10 @@ namespace System.Net
                     }
                 }
             }
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal void Abort()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ForceCancelRequest(RequestQueueHandle, Request.RequestId);
             try
             {
@@ -116,7 +112,6 @@ namespace System.Net
             {
                 (_user?.Identity as IDisposable)?.Dispose();
             }
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         internal Interop.HttpApi.HTTP_VERB GetKnownMethod()
index 4d21bf1..86629c7 100644 (file)
@@ -216,12 +216,10 @@ namespace System.Net
         {
             get
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
                 if (_requestStream == null)
                 {
                     _requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
                 }
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 return _requestStream;
             }
         }
@@ -256,31 +254,25 @@ namespace System.Net
 
         public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             X509Certificate2 clientCertificate = null;
-            try
+
+            if (asyncResult == null)
             {
-                if (asyncResult == null)
-                {
-                    throw new ArgumentNullException(nameof(asyncResult));
-                }
-                ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
-                if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
-                {
-                    throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
-                }
-                if (clientCertAsyncResult.EndCalled)
-                {
-                    throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
-                }
-                clientCertAsyncResult.EndCalled = true;
-                clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
+                throw new ArgumentNullException(nameof(asyncResult));
             }
-            finally
+            ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
+            if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+                throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
             }
+            if (clientCertAsyncResult.EndCalled)
+            {
+                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
+            }
+            clientCertAsyncResult.EndCalled = true;
+            clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
+
             return clientCertificate;
         }
 
@@ -325,7 +317,6 @@ namespace System.Net
         //should only be called from httplistenercontext
         internal void Close()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             RequestContextBase memoryBlob = _memoryBlob;
             if (memoryBlob != null)
             {
@@ -333,7 +324,6 @@ namespace System.Net
                 _memoryBlob = null;
             }
             _isDisposed = true;
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback requestCallback, object state)
index ba3b3ee..3dcc2d7 100644 (file)
@@ -97,26 +97,17 @@ namespace System.Net
 
         public void Abort()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-            try
-            {
-                if (Disposed)
-                {
-                    return;
-                }
-
-                _responseState = ResponseState.Closed;
-                HttpListenerContext.Abort();
-            }
-            finally
+            if (Disposed)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+                return;
             }
+
+            _responseState = ResponseState.Closed;
+            HttpListenerContext.Abort();
         }
 
         public void Close()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this);
@@ -124,50 +115,41 @@ namespace System.Net
             }
             finally
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             }
         }
 
         public void Close(byte[] responseEntity, bool willBlock)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"responseEntity={responseEntity},willBlock={willBlock}");
-            try
+            CheckDisposed();
+            if (responseEntity == null)
             {
-                CheckDisposed();
-                if (responseEntity == null)
-                {
-                    throw new ArgumentNullException(nameof(responseEntity));
-                }
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ResponseState:{_responseState}, BoundaryType:{_boundaryType}, ContentLength:{_contentLength}");
-                if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
+                throw new ArgumentNullException(nameof(responseEntity));
+            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ResponseState:{_responseState}, BoundaryType:{_boundaryType}, ContentLength:{_contentLength}");
+            if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
+            {
+                ContentLength64 = responseEntity.Length;
+            }
+            EnsureResponseStream();
+            if (willBlock)
+            {
+                try
                 {
-                    ContentLength64 = responseEntity.Length;
+                    _responseStream.Write(responseEntity, 0, responseEntity.Length);
                 }
-                EnsureResponseStream();
-                if (willBlock)
+                catch (Win32Exception)
                 {
-                    try
-                    {
-                        _responseStream.Write(responseEntity, 0, responseEntity.Length);
-                    }
-                    catch (Win32Exception)
-                    {
-                    }
-                    finally
-                    {
-                        _responseStream.Close();
-                        _responseState = ResponseState.Closed;
-                        HttpListenerContext.Close();
-                    }
                 }
-                else
+                finally
                 {
-                    _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
+                    _responseStream.Close();
+                    _responseState = ResponseState.Closed;
+                    HttpListenerContext.Close();
                 }
             }
-            finally
+            else
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+                _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
             }
         }
 
index af2b08e..6bc057e 100644 (file)
@@ -103,7 +103,6 @@ namespace System.Net
             {
                 NetEventSource.DumpBuffer(this, buffer, offset, (int)dataRead);
                 NetEventSource.Info(this, "returning dataRead:" + dataRead);
-                NetEventSource.Exit(this, "dataRead:" + dataRead);
             }
             return (int)dataRead;
         }
@@ -122,7 +121,6 @@ namespace System.Net
         {
             if (size == 0 || _closed)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 HttpRequestStreamAsyncResult result = new HttpRequestStreamAsyncResult(this, state, callback);
                 result.InvokeCallback((uint)0);
                 return result;
@@ -214,17 +212,13 @@ namespace System.Net
                     asyncResult.IOCompleted(statusCode, bytesReturned);
                 }
             }
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return asyncResult;
         }
 
         public override int EndRead(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"asyncResult: {asyncResult}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult: {asyncResult}");
+
             if (asyncResult == null)
             {
                 throw new ArgumentNullException(nameof(asyncResult));
@@ -254,11 +248,7 @@ namespace System.Net
 
             uint dataRead = (uint)returnValue;
             UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead);
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Info(this, $"returnValue:{returnValue}");
-                NetEventSource.Exit(this);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"returnValue:{returnValue}");
 
             return (int)dataRead + (int)castedAsyncResult._dataAlreadyRead;
         }
index 731d7cc..4f2e22c 100644 (file)
@@ -52,7 +52,6 @@ namespace System.Net
             Interop.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
             if (size == 0 && _leftToWrite != 0)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 return;
             }
             if (_leftToWrite >= 0 && size > _leftToWrite)
@@ -145,7 +144,6 @@ namespace System.Net
             }
             UpdateAfterWrite(dataToWrite);
             if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, (int)dataToWrite);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
@@ -153,7 +151,6 @@ namespace System.Net
             Interop.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
             if (_closed || (size == 0 && _leftToWrite != 0))
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 HttpResponseStreamAsyncResult result = new HttpResponseStreamAsyncResult(this, state, callback);
                 result.InvokeCallback((uint)0);
                 return result;
@@ -236,7 +233,6 @@ namespace System.Net
                 _lastWrite = asyncResult;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return asyncResult;
         }
 
@@ -264,7 +260,6 @@ namespace System.Net
                 ExceptionDispatchInfo.Throw(exception);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private void UpdateAfterWrite(uint dataWritten)
@@ -298,8 +293,6 @@ namespace System.Net
             bool sentHeaders = _httpContext.Response.SentHeaders;
             if (sentHeaders && _leftToWrite == 0)
             {
-                if (NetEventSource.Log.IsEnabled())
-                    NetEventSource.Exit(this);
                 return;
             }
 
index 1e11b6d..bab0370 100644 (file)
@@ -51,8 +51,6 @@ namespace System.Net
 
         private static byte[] GetChunkHeader(int size, out int offset)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, $"size:{size}");
-
             uint Mask = 0xf0000000;
             byte[] Header = new byte[10];
             int i;
@@ -106,7 +104,6 @@ namespace System.Net
             Header[8] = (byte)'\r';
             Header[9] = (byte)'\n';
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
             return Header;
         }
 
index 45146b3..fbf3d12 100644 (file)
@@ -33,11 +33,6 @@ namespace System.Net.WebSockets
             ArraySegment<byte> internalBuffer)
         {
             HttpListenerWebSocketContext webSocketContext = null;
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(null, context);
-            }
-
             try
             {
                 // get property will create a new response if one doesn't exist.
@@ -137,13 +132,6 @@ namespace System.Net.WebSockets
                 }
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(context);
-                }
-            }
 
             return webSocketContext;
         }
index 3dc973b..2d72978 100644 (file)
@@ -75,45 +75,33 @@ namespace System.Net.WebSockets
                     keepAliveInterval,
                     NetEventSource.GetHashCode(innerStream),
                     NetEventSource.GetHashCode(internalBuffer));
-
-                NetEventSource.Enter(this, parameters);
             }
 
             _thisLock = new object();
 
-            try
+            _innerStream = innerStream;
+            _internalBuffer = internalBuffer;
+            if (NetEventSource.Log.IsEnabled())
             {
-                _innerStream = innerStream;
-                _internalBuffer = internalBuffer;
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Associate(this, _innerStream);
-                    NetEventSource.Associate(this, _internalBuffer);
-                }
-
-                _closeOutstandingOperationHelper = new OutstandingOperationHelper();
-                _closeOutputOutstandingOperationHelper = new OutstandingOperationHelper();
-                _receiveOutstandingOperationHelper = new OutstandingOperationHelper();
-                _sendOutstandingOperationHelper = new OutstandingOperationHelper();
-                _state = WebSocketState.Open;
-                _subProtocol = subProtocol;
-                _sendFrameThrottle = new SemaphoreSlim(1, 1);
-                _closeStatus = null;
-                _closeStatusDescription = null;
-                _innerStreamAsWebSocketStream = innerStream as IWebSocketStream;
-                if (_innerStreamAsWebSocketStream != null)
-                {
-                    _innerStreamAsWebSocketStream.SwitchToOpaqueMode(this);
-                }
-                _keepAliveTracker = KeepAliveTracker.Create(keepAliveInterval);
+                NetEventSource.Associate(this, _innerStream);
+                NetEventSource.Associate(this, _internalBuffer);
             }
-            finally
+
+            _closeOutstandingOperationHelper = new OutstandingOperationHelper();
+            _closeOutputOutstandingOperationHelper = new OutstandingOperationHelper();
+            _receiveOutstandingOperationHelper = new OutstandingOperationHelper();
+            _sendOutstandingOperationHelper = new OutstandingOperationHelper();
+            _state = WebSocketState.Open;
+            _subProtocol = subProtocol;
+            _sendFrameThrottle = new SemaphoreSlim(1, 1);
+            _closeStatus = null;
+            _closeStatusDescription = null;
+            _innerStreamAsWebSocketStream = innerStream as IWebSocketStream;
+            if (_innerStreamAsWebSocketStream != null)
             {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this, parameters);
-                }
+                _innerStreamAsWebSocketStream.SwitchToOpaqueMode(this);
             }
+            _keepAliveTracker = KeepAliveTracker.Create(keepAliveInterval);
         }
 
         public override WebSocketState State
@@ -181,65 +169,51 @@ namespace System.Net.WebSockets
         private async Task<WebSocketReceiveResult> ReceiveAsyncCore(ArraySegment<byte> buffer,
             CancellationToken cancellationToken)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-            }
-
             WebSocketReceiveResult receiveResult;
+
+            ThrowIfPendingException();
+            ThrowIfDisposed();
+            ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseSent);
+
+            bool ownsCancellationTokenSource = false;
+            CancellationToken linkedCancellationToken = CancellationToken.None;
             try
             {
-                ThrowIfPendingException();
-                ThrowIfDisposed();
-                ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseSent);
-
-                bool ownsCancellationTokenSource = false;
-                CancellationToken linkedCancellationToken = CancellationToken.None;
-                try
+                ownsCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken,
+                    out linkedCancellationToken);
+                if (!ownsCancellationTokenSource)
                 {
-                    ownsCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken,
-                        out linkedCancellationToken);
-                    if (!ownsCancellationTokenSource)
+                    lock (_thisLock)
                     {
-                        lock (_thisLock)
+                        if (_closeAsyncStartedReceive)
                         {
-                            if (_closeAsyncStartedReceive)
-                            {
-                                throw new InvalidOperationException(
-                                    SR.Format(SR.net_WebSockets_ReceiveAsyncDisallowedAfterCloseAsync, nameof(CloseAsync), nameof(CloseOutputAsync)));
-                            }
-
                             throw new InvalidOperationException(
-                                SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(ReceiveAsync)));
+                                SR.Format(SR.net_WebSockets_ReceiveAsyncDisallowedAfterCloseAsync, nameof(CloseAsync), nameof(CloseOutputAsync)));
                         }
-                    }
 
-                    EnsureReceiveOperation();
-                    receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
-
-                    if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
-                    {
-                        NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count);
+                        throw new InvalidOperationException(
+                            SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(ReceiveAsync)));
                     }
                 }
-                catch (Exception exception)
-                {
-                    bool aborted = linkedCancellationToken.IsCancellationRequested;
-                    Abort();
-                    ThrowIfConvertibleException(nameof(ReceiveAsync), exception, cancellationToken, aborted);
-                    throw;
-                }
-                finally
+
+                EnsureReceiveOperation();
+                receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
+
+                if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
                 {
-                    _receiveOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
+                    NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count);
                 }
             }
+            catch (Exception exception)
+            {
+                bool aborted = linkedCancellationToken.IsCancellationRequested;
+                Abort();
+                ThrowIfConvertibleException(nameof(ReceiveAsync), exception, cancellationToken, aborted);
+                throw;
+            }
             finally
             {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this);
-                }
+                _receiveOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
             }
 
             return receiveResult;
@@ -284,78 +258,67 @@ namespace System.Net.WebSockets
                     "messageType: {0}, endOfMessage: {1}",
                     messageType,
                     endOfMessage);
-                NetEventSource.Enter(this, inputParameter);
             }
 
+            ThrowIfPendingException();
+            ThrowIfDisposed();
+            ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
+            bool ownsCancellationTokenSource = false;
+            CancellationToken linkedCancellationToken = CancellationToken.None;
+
             try
             {
-                ThrowIfPendingException();
-                ThrowIfDisposed();
-                ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
-                bool ownsCancellationTokenSource = false;
-                CancellationToken linkedCancellationToken = CancellationToken.None;
-
-                try
+                while (!(ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken)))
                 {
-                    while (!(ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken)))
+                    Task keepAliveTask;
+
+                    lock (SessionHandle)
                     {
-                        Task keepAliveTask;
+                        keepAliveTask = _keepAliveTask;
 
-                        lock (SessionHandle)
+                        if (keepAliveTask == null)
                         {
-                            keepAliveTask = _keepAliveTask;
-
-                            if (keepAliveTask == null)
+                            // Check whether there is still another outstanding send operation
+                            // Potentially the keepAlive operation has completed before this thread
+                            // was able to enter the SessionHandle-lock.
+                            _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
+                            if (ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))
                             {
-                                // Check whether there is still another outstanding send operation
-                                // Potentially the keepAlive operation has completed before this thread
-                                // was able to enter the SessionHandle-lock.
-                                _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
-                                if (ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))
-                                {
-                                    break;
-                                }
-                                else
-                                {
-                                    throw new InvalidOperationException(
-                                        SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
-                                }
+                                break;
+                            }
+                            else
+                            {
+                                throw new InvalidOperationException(
+                                    SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
                             }
                         }
-
-                        await keepAliveTask.SuppressContextFlow();
-                        ThrowIfPendingException();
-
-                        _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
                     }
 
-                    if (NetEventSource.Log.IsEnabled() && buffer.Count > 0)
-                    {
-                        NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count);
-                    }
+                    await keepAliveTask.SuppressContextFlow();
+                    ThrowIfPendingException();
 
-                    EnsureSendOperation();
-                    _sendOperation.BufferType = GetBufferType(messageType, endOfMessage);
-                    await _sendOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
-                }
-                catch (Exception exception)
-                {
-                    bool aborted = linkedCancellationToken.IsCancellationRequested;
-                    Abort();
-                    ThrowIfConvertibleException(nameof(SendAsync), exception, cancellationToken, aborted);
-                    throw;
+                    _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
                 }
-                finally
+
+                if (NetEventSource.Log.IsEnabled() && buffer.Count > 0)
                 {
-                    _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
+                    NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count);
                 }
+
+                EnsureSendOperation();
+                _sendOperation.BufferType = GetBufferType(messageType, endOfMessage);
+                await _sendOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
+            }
+            catch (Exception exception)
+            {
+                bool aborted = linkedCancellationToken.IsCancellationRequested;
+                Abort();
+                ThrowIfConvertibleException(nameof(SendAsync), exception, cancellationToken, aborted);
+                throw;
             }
             finally
             {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this, inputParameter);
-                }
+                _sendOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
             }
         }
 
@@ -405,11 +368,6 @@ namespace System.Net.WebSockets
         // MultiThreading: ThreadSafe; No-op if already in a terminal state
         public override void Abort()
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-            }
-
             bool thisLockTaken = false;
             bool sessionHandleLockTaken = false;
             try
@@ -446,10 +404,6 @@ namespace System.Net.WebSockets
             finally
             {
                 ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this);
-                }
             }
         }
 
@@ -474,134 +428,123 @@ namespace System.Net.WebSockets
                     "closeStatus: {0}, statusDescription: {1}",
                     closeStatus,
                     statusDescription);
-                NetEventSource.Enter(this, inputParameter);
             }
 
+            ThrowIfPendingException();
+            if (IsStateTerminal(State))
+            {
+                return;
+            }
+            ThrowIfDisposed();
+
+            bool thisLockTaken = false;
+            bool sessionHandleLockTaken = false;
+            bool needToCompleteSendOperation = false;
+            bool ownsCloseOutputCancellationTokenSource = false;
+            bool ownsSendCancellationTokenSource = false;
+            CancellationToken linkedCancellationToken = CancellationToken.None;
             try
             {
+                TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
                 ThrowIfPendingException();
+                ThrowIfDisposed();
+
                 if (IsStateTerminal(State))
                 {
                     return;
                 }
-                ThrowIfDisposed();
 
-                bool thisLockTaken = false;
-                bool sessionHandleLockTaken = false;
-                bool needToCompleteSendOperation = false;
-                bool ownsCloseOutputCancellationTokenSource = false;
-                bool ownsSendCancellationTokenSource = false;
-                CancellationToken linkedCancellationToken = CancellationToken.None;
-                try
+                ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
+                ownsCloseOutputCancellationTokenSource = _closeOutputOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+                if (!ownsCloseOutputCancellationTokenSource)
                 {
-                    TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                    ThrowIfPendingException();
-                    ThrowIfDisposed();
+                    Task closeOutputTask = _closeOutputTask;
 
-                    if (IsStateTerminal(State))
+                    if (closeOutputTask != null)
                     {
-                        return;
+                        ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+                        await closeOutputTask.SuppressContextFlow();
+                        TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
                     }
-
-                    ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived);
-                    ownsCloseOutputCancellationTokenSource = _closeOutputOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
-                    if (!ownsCloseOutputCancellationTokenSource)
+                }
+                else
+                {
+                    needToCompleteSendOperation = true;
+                    while (!(ownsSendCancellationTokenSource =
+                        _sendOutstandingOperationHelper.TryStartOperation(cancellationToken,
+                            out linkedCancellationToken)))
                     {
-                        Task closeOutputTask = _closeOutputTask;
-
-                        if (closeOutputTask != null)
+                        if (_keepAliveTask != null)
                         {
+                            Task keepAliveTask = _keepAliveTask;
+
                             ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                            await closeOutputTask.SuppressContextFlow();
+                            await keepAliveTask.SuppressContextFlow();
                             TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+
+                            ThrowIfPendingException();
                         }
-                    }
-                    else
-                    {
-                        needToCompleteSendOperation = true;
-                        while (!(ownsSendCancellationTokenSource =
-                            _sendOutstandingOperationHelper.TryStartOperation(cancellationToken,
-                                out linkedCancellationToken)))
+                        else
                         {
-                            if (_keepAliveTask != null)
-                            {
-                                Task keepAliveTask = _keepAliveTask;
-
-                                ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                                await keepAliveTask.SuppressContextFlow();
-                                TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-
-                                ThrowIfPendingException();
-                            }
-                            else
-                            {
-                                throw new InvalidOperationException(
-                                    SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
-                            }
-
-                            _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
+                            throw new InvalidOperationException(
+                                SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(SendAsync)));
                         }
 
-                        EnsureCloseOutputOperation();
-                        _closeOutputOperation.CloseStatus = closeStatus;
-                        _closeOutputOperation.CloseReason = statusDescription;
-                        _closeOutputTask = _closeOutputOperation.Process(null, linkedCancellationToken);
+                        _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
+                    }
 
-                        ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                        await _closeOutputTask.SuppressContextFlow();
-                        TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+                    EnsureCloseOutputOperation();
+                    _closeOutputOperation.CloseStatus = closeStatus;
+                    _closeOutputOperation.CloseReason = statusDescription;
+                    _closeOutputTask = _closeOutputOperation.Process(null, linkedCancellationToken);
 
-                        if (OnCloseOutputCompleted())
-                        {
-                            bool callCompleteOnCloseCompleted = false;
+                    ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+                    await _closeOutputTask.SuppressContextFlow();
+                    TakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
 
-                            try
-                            {
-                                callCompleteOnCloseCompleted = await StartOnCloseCompleted(
-                                    thisLockTaken, sessionHandleLockTaken, linkedCancellationToken).SuppressContextFlow();
-                            }
-                            catch (Exception)
-                            {
-                                // If an exception is thrown we know that the locks have been released,
-                                // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
-                                ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                                throw;
-                            }
+                    if (OnCloseOutputCompleted())
+                    {
+                        bool callCompleteOnCloseCompleted = false;
 
-                            if (callCompleteOnCloseCompleted)
-                            {
-                                ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
-                                FinishOnCloseCompleted();
-                            }
+                        try
+                        {
+                            callCompleteOnCloseCompleted = await StartOnCloseCompleted(
+                                thisLockTaken, sessionHandleLockTaken, linkedCancellationToken).SuppressContextFlow();
+                        }
+                        catch (Exception)
+                        {
+                            // If an exception is thrown we know that the locks have been released,
+                            // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
+                            ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+                            throw;
                         }
-                    }
-                }
-                catch (Exception exception)
-                {
-                    bool aborted = linkedCancellationToken.IsCancellationRequested;
-                    Abort();
-                    ThrowIfConvertibleException(nameof(CloseOutputAsync), exception, cancellationToken, aborted);
-                    throw;
-                }
-                finally
-                {
-                    _closeOutputOutstandingOperationHelper.CompleteOperation(ownsCloseOutputCancellationTokenSource);
 
-                    if (needToCompleteSendOperation)
-                    {
-                        _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
+                        if (callCompleteOnCloseCompleted)
+                        {
+                            ResetFlagsAndTakeLocks(ref thisLockTaken, ref sessionHandleLockTaken);
+                            FinishOnCloseCompleted();
+                        }
                     }
-
-                    _closeOutputTask = null;
-                    ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
                 }
             }
+            catch (Exception exception)
+            {
+                bool aborted = linkedCancellationToken.IsCancellationRequested;
+                Abort();
+                ThrowIfConvertibleException(nameof(CloseOutputAsync), exception, cancellationToken, aborted);
+                throw;
+            }
             finally
             {
-                if (NetEventSource.Log.IsEnabled())
+                _closeOutputOutstandingOperationHelper.CompleteOperation(ownsCloseOutputCancellationTokenSource);
+
+                if (needToCompleteSendOperation)
                 {
-                    NetEventSource.Exit(this, inputParameter);
+                    _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationTokenSource);
                 }
+
+                _closeOutputTask = null;
+                ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken);
             }
         }
 
@@ -712,9 +655,19 @@ namespace System.Net.WebSockets
                     "closeStatus: {0}, statusDescription: {1}",
                     closeStatus,
                     statusDescription);
-                NetEventSource.Enter(this, inputParameter);
             }
 
+            ThrowIfPendingException();
+            if (IsStateTerminal(State))
+            {
+                return;
+            }
+            ThrowIfDisposed();
+
+            bool lockTaken = false;
+            Monitor.Enter(_thisLock, ref lockTaken);
+            bool ownsCloseCancellationTokenSource = false;
+            CancellationToken linkedCancellationToken = CancellationToken.None;
             try
             {
                 ThrowIfPendingException();
@@ -723,73 +676,166 @@ namespace System.Net.WebSockets
                     return;
                 }
                 ThrowIfDisposed();
+                ThrowOnInvalidState(State,
+                    WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent);
 
-                bool lockTaken = false;
-                Monitor.Enter(_thisLock, ref lockTaken);
-                bool ownsCloseCancellationTokenSource = false;
-                CancellationToken linkedCancellationToken = CancellationToken.None;
-                try
+                Task closeOutputTask;
+                ownsCloseCancellationTokenSource = _closeOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+                if (ownsCloseCancellationTokenSource)
                 {
-                    ThrowIfPendingException();
-                    if (IsStateTerminal(State))
+                    closeOutputTask = _closeOutputTask;
+                    if (closeOutputTask == null && State != WebSocketState.CloseSent)
                     {
-                        return;
+                        _closeReceivedTaskCompletionSource ??= new TaskCompletionSource();
+
+                        closeOutputTask = CloseOutputAsync(closeStatus,
+                            statusDescription,
+                            linkedCancellationToken);
                     }
-                    ThrowIfDisposed();
-                    ThrowOnInvalidState(State,
-                        WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent);
+                }
+                else
+                {
+                    Debug.Assert(_closeReceivedTaskCompletionSource != null, "'_closeReceivedTaskCompletionSource' MUST NOT be NULL.");
+                    closeOutputTask = _closeReceivedTaskCompletionSource.Task;
+                }
 
-                    Task closeOutputTask;
-                    ownsCloseCancellationTokenSource = _closeOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
-                    if (ownsCloseCancellationTokenSource)
+                if (closeOutputTask != null)
+                {
+                    ReleaseLock(_thisLock, ref lockTaken);
+                    try
                     {
-                        closeOutputTask = _closeOutputTask;
-                        if (closeOutputTask == null && State != WebSocketState.CloseSent)
-                        {
-                            _closeReceivedTaskCompletionSource ??= new TaskCompletionSource();
+                        await closeOutputTask.SuppressContextFlow();
+                    }
+                    catch (Exception closeOutputError)
+                    {
+                        Monitor.Enter(_thisLock, ref lockTaken);
 
-                            closeOutputTask = CloseOutputAsync(closeStatus,
-                                statusDescription,
-                                linkedCancellationToken);
+                        if (!CanHandleExceptionDuringClose(closeOutputError))
+                        {
+                            ThrowIfConvertibleException(nameof(CloseOutputAsync),
+                                closeOutputError,
+                                cancellationToken,
+                                linkedCancellationToken.IsCancellationRequested);
+                            throw;
                         }
                     }
-                    else
+
+                    // When closeOutputTask != null  and an exception thrown from await closeOutputTask is handled,
+                    // the lock will be taken in the catch-block. So the logic here avoids taking the lock twice.
+                    if (!lockTaken)
                     {
-                        Debug.Assert(_closeReceivedTaskCompletionSource != null, "'_closeReceivedTaskCompletionSource' MUST NOT be NULL.");
-                        closeOutputTask = _closeReceivedTaskCompletionSource.Task;
+                        Monitor.Enter(_thisLock, ref lockTaken);
                     }
+                }
 
-                    if (closeOutputTask != null)
+                if (OnCloseOutputCompleted())
+                {
+                    bool callCompleteOnCloseCompleted = false;
+
+                    try
                     {
-                        ReleaseLock(_thisLock, ref lockTaken);
-                        try
+                        // linkedCancellationToken can be CancellationToken.None if ownsCloseCancellationTokenSource==false
+                        // This is still ok because OnCloseOutputCompleted won't start any IO operation in this case
+                        callCompleteOnCloseCompleted = await StartOnCloseCompleted(
+                            lockTaken, false, linkedCancellationToken).SuppressContextFlow();
+                    }
+                    catch (Exception)
+                    {
+                        // If an exception is thrown we know that the locks have been released,
+                        // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
+                        ResetFlagAndTakeLock(_thisLock, ref lockTaken);
+                        throw;
+                    }
+
+                    if (callCompleteOnCloseCompleted)
+                    {
+                        ResetFlagAndTakeLock(_thisLock, ref lockTaken);
+                        FinishOnCloseCompleted();
+                    }
+                }
+
+                if (IsStateTerminal(State))
+                {
+                    return;
+                }
+
+                linkedCancellationToken = CancellationToken.None;
+
+                bool ownsReceiveCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+                if (ownsReceiveCancellationTokenSource)
+                {
+                    _closeAsyncStartedReceive = true;
+                    ArraySegment<byte> closeMessageBuffer =
+                        new ArraySegment<byte>(new byte[HttpWebSocket.MinReceiveBufferSize]);
+                    EnsureReceiveOperation();
+                    Task<WebSocketReceiveResult> receiveAsyncTask = _receiveOperation.Process(closeMessageBuffer,
+                        linkedCancellationToken);
+                    ReleaseLock(_thisLock, ref lockTaken);
+
+                    WebSocketReceiveResult receiveResult = null;
+                    try
+                    {
+                        receiveResult = await receiveAsyncTask.SuppressContextFlow();
+                    }
+                    catch (Exception receiveException)
+                    {
+                        Monitor.Enter(_thisLock, ref lockTaken);
+
+                        if (!CanHandleExceptionDuringClose(receiveException))
                         {
-                            await closeOutputTask.SuppressContextFlow();
+                            ThrowIfConvertibleException(nameof(CloseAsync),
+                                receiveException,
+                                cancellationToken,
+                                linkedCancellationToken.IsCancellationRequested);
+                            throw;
                         }
-                        catch (Exception closeOutputError)
-                        {
-                            Monitor.Enter(_thisLock, ref lockTaken);
+                    }
 
-                            if (!CanHandleExceptionDuringClose(closeOutputError))
-                            {
-                                ThrowIfConvertibleException(nameof(CloseOutputAsync),
-                                    closeOutputError,
-                                    cancellationToken,
-                                    linkedCancellationToken.IsCancellationRequested);
-                                throw;
-                            }
+                    // receiveResult is NEVER NULL if WebSocketBase.ReceiveOperation.Process completes successfully
+                    // - but in the close code path we handle some exception if another thread was able to tranistion
+                    // the state into Closed successfully. In this case receiveResult can be NULL and it is safe to
+                    // skip the statements in the if-block.
+                    if (receiveResult != null)
+                    {
+                        if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
+                        {
+                            NetEventSource.DumpBuffer(this, closeMessageBuffer.Array, closeMessageBuffer.Offset, receiveResult.Count);
                         }
 
-                        // When closeOutputTask != null  and an exception thrown from await closeOutputTask is handled,
-                        // the lock will be taken in the catch-block. So the logic here avoids taking the lock twice.
-                        if (!lockTaken)
+                        if (receiveResult.MessageType != WebSocketMessageType.Close)
                         {
-                            Monitor.Enter(_thisLock, ref lockTaken);
+                            throw new WebSocketException(WebSocketError.InvalidMessageType,
+                                SR.Format(SR.net_WebSockets_InvalidMessageType,
+                                    typeof(WebSocket).Name + "." + nameof(CloseAsync),
+                                    typeof(WebSocket).Name + "." + nameof(CloseOutputAsync),
+                                    receiveResult.MessageType));
                         }
                     }
+                }
+                else
+                {
+                    _receiveOutstandingOperationHelper.CompleteOperation(ownsReceiveCancellationTokenSource);
+                    ReleaseLock(_thisLock, ref lockTaken);
+                    await _closeReceivedTaskCompletionSource.Task.SuppressContextFlow();
+                }
 
-                    if (OnCloseOutputCompleted())
+                // When ownsReceiveCancellationTokenSource is true and an exception is thrown, the lock will be taken.
+                // So this logic here is to avoid taking the lock twice.
+                if (!lockTaken)
+                {
+                    Monitor.Enter(_thisLock, ref lockTaken);
+                }
+
+                if (!IsStateTerminal(State))
+                {
+                    bool ownsSendCancellationSource = false;
+                    try
                     {
+                        // We know that the CloseFrame has been sent at this point. So no Send-operation is allowed anymore and we
+                        // can hijack the _SendOutstandingOperationHelper to create a linkedCancellationToken
+                        ownsSendCancellationSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
+                        Debug.Assert(ownsSendCancellationSource, "'ownsSendCancellationSource' MUST be 'true' at this point.");
+
                         bool callCompleteOnCloseCompleted = false;
 
                         try
@@ -813,137 +859,23 @@ namespace System.Net.WebSockets
                             FinishOnCloseCompleted();
                         }
                     }
-
-                    if (IsStateTerminal(State))
-                    {
-                        return;
-                    }
-
-                    linkedCancellationToken = CancellationToken.None;
-
-                    bool ownsReceiveCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
-                    if (ownsReceiveCancellationTokenSource)
-                    {
-                        _closeAsyncStartedReceive = true;
-                        ArraySegment<byte> closeMessageBuffer =
-                            new ArraySegment<byte>(new byte[HttpWebSocket.MinReceiveBufferSize]);
-                        EnsureReceiveOperation();
-                        Task<WebSocketReceiveResult> receiveAsyncTask = _receiveOperation.Process(closeMessageBuffer,
-                            linkedCancellationToken);
-                        ReleaseLock(_thisLock, ref lockTaken);
-
-                        WebSocketReceiveResult receiveResult = null;
-                        try
-                        {
-                            receiveResult = await receiveAsyncTask.SuppressContextFlow();
-                        }
-                        catch (Exception receiveException)
-                        {
-                            Monitor.Enter(_thisLock, ref lockTaken);
-
-                            if (!CanHandleExceptionDuringClose(receiveException))
-                            {
-                                ThrowIfConvertibleException(nameof(CloseAsync),
-                                    receiveException,
-                                    cancellationToken,
-                                    linkedCancellationToken.IsCancellationRequested);
-                                throw;
-                            }
-                        }
-
-                        // receiveResult is NEVER NULL if WebSocketBase.ReceiveOperation.Process completes successfully
-                        // - but in the close code path we handle some exception if another thread was able to tranistion
-                        // the state into Closed successfully. In this case receiveResult can be NULL and it is safe to
-                        // skip the statements in the if-block.
-                        if (receiveResult != null)
-                        {
-                            if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0)
-                            {
-                                NetEventSource.DumpBuffer(this, closeMessageBuffer.Array, closeMessageBuffer.Offset, receiveResult.Count);
-                            }
-
-                            if (receiveResult.MessageType != WebSocketMessageType.Close)
-                            {
-                                throw new WebSocketException(WebSocketError.InvalidMessageType,
-                                    SR.Format(SR.net_WebSockets_InvalidMessageType,
-                                        typeof(WebSocket).Name + "." + nameof(CloseAsync),
-                                        typeof(WebSocket).Name + "." + nameof(CloseOutputAsync),
-                                        receiveResult.MessageType));
-                            }
-                        }
-                    }
-                    else
-                    {
-                        _receiveOutstandingOperationHelper.CompleteOperation(ownsReceiveCancellationTokenSource);
-                        ReleaseLock(_thisLock, ref lockTaken);
-                        await _closeReceivedTaskCompletionSource.Task.SuppressContextFlow();
-                    }
-
-                    // When ownsReceiveCancellationTokenSource is true and an exception is thrown, the lock will be taken.
-                    // So this logic here is to avoid taking the lock twice.
-                    if (!lockTaken)
+                    finally
                     {
-                        Monitor.Enter(_thisLock, ref lockTaken);
+                        _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationSource);
                     }
-
-                    if (!IsStateTerminal(State))
-                    {
-                        bool ownsSendCancellationSource = false;
-                        try
-                        {
-                            // We know that the CloseFrame has been sent at this point. So no Send-operation is allowed anymore and we
-                            // can hijack the _SendOutstandingOperationHelper to create a linkedCancellationToken
-                            ownsSendCancellationSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken);
-                            Debug.Assert(ownsSendCancellationSource, "'ownsSendCancellationSource' MUST be 'true' at this point.");
-
-                            bool callCompleteOnCloseCompleted = false;
-
-                            try
-                            {
-                                // linkedCancellationToken can be CancellationToken.None if ownsCloseCancellationTokenSource==false
-                                // This is still ok because OnCloseOutputCompleted won't start any IO operation in this case
-                                callCompleteOnCloseCompleted = await StartOnCloseCompleted(
-                                    lockTaken, false, linkedCancellationToken).SuppressContextFlow();
-                            }
-                            catch (Exception)
-                            {
-                                // If an exception is thrown we know that the locks have been released,
-                                // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield
-                                ResetFlagAndTakeLock(_thisLock, ref lockTaken);
-                                throw;
-                            }
-
-                            if (callCompleteOnCloseCompleted)
-                            {
-                                ResetFlagAndTakeLock(_thisLock, ref lockTaken);
-                                FinishOnCloseCompleted();
-                            }
-                        }
-                        finally
-                        {
-                            _sendOutstandingOperationHelper.CompleteOperation(ownsSendCancellationSource);
-                        }
-                    }
-                }
-                catch (Exception exception)
-                {
-                    bool aborted = linkedCancellationToken.IsCancellationRequested;
-                    Abort();
-                    ThrowIfConvertibleException(nameof(CloseAsync), exception, cancellationToken, aborted);
-                    throw;
-                }
-                finally
-                {
-                    _closeOutstandingOperationHelper.CompleteOperation(ownsCloseCancellationTokenSource);
-                    ReleaseLock(_thisLock, ref lockTaken);
                 }
             }
+            catch (Exception exception)
+            {
+                bool aborted = linkedCancellationToken.IsCancellationRequested;
+                Abort();
+                ThrowIfConvertibleException(nameof(CloseAsync), exception, cancellationToken, aborted);
+                throw;
+            }
             finally
             {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this, inputParameter);
-                }
+                _closeOutstandingOperationHelper.CompleteOperation(ownsCloseCancellationTokenSource);
+                ReleaseLock(_thisLock, ref lockTaken);
             }
         }
 
@@ -1423,11 +1355,6 @@ namespace System.Net.WebSockets
             WebSocketBase thisPtr = sender as WebSocketBase;
             bool lockTaken = false;
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(thisPtr);
-            }
-
             CancellationToken linkedCancellationToken = CancellationToken.None;
             try
             {
@@ -1485,11 +1412,6 @@ namespace System.Net.WebSockets
             finally
             {
                 ReleaseLock(thisPtr.SessionHandle, ref lockTaken);
-
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(thisPtr);
-                }
             }
         }
 
index 8630bf8..151a958 100644 (file)
@@ -127,11 +127,6 @@ namespace System.Net.WebSockets
 
         private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
-            }
-
             CancellationTokenRegistration cancellationTokenRegistration = default;
 
             int bytesRead = 0;
@@ -184,11 +179,6 @@ namespace System.Net.WebSockets
             finally
             {
                 cancellationTokenRegistration.Dispose();
-
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this, bytesRead);
-                }
             }
 
             return bytesRead;
@@ -199,11 +189,6 @@ namespace System.Net.WebSockets
         // true: async completion or error
         private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-            }
-
             eventArgs.StartOperationCommon(this, _inputStream.InternalHttpContext.RequestQueueBoundHandle);
             eventArgs.StartOperationReceive();
 
@@ -297,13 +282,6 @@ namespace System.Net.WebSockets
 
                 completedAsynchronouslyOrWithError = true;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this, completedAsynchronouslyOrWithError);
-                }
-            }
 
             return completedAsynchronouslyOrWithError;
         }
@@ -356,11 +334,6 @@ namespace System.Net.WebSockets
             Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
             Debug.Assert(sendBuffers.Count == 2, "'sendBuffers.Count' MUST be '2' at this point.");
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-            }
-
             CancellationTokenRegistration cancellationTokenRegistration = default;
 
             try
@@ -396,11 +369,6 @@ namespace System.Net.WebSockets
             finally
             {
                 cancellationTokenRegistration.Dispose();
-
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this);
-                }
             }
         }
 
@@ -418,11 +386,6 @@ namespace System.Net.WebSockets
 
         private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
-            }
-
             CancellationTokenRegistration cancellationTokenRegistration = default;
 
             try
@@ -466,11 +429,6 @@ namespace System.Net.WebSockets
             finally
             {
                 cancellationTokenRegistration.Dispose();
-
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this);
-                }
             }
         }
 
@@ -479,11 +437,6 @@ namespace System.Net.WebSockets
         // true: async completion or with error
         private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-            }
-
             Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE;
 
             eventArgs.StartOperationCommon(this, _outputStream.InternalHttpContext.RequestQueueBoundHandle);
@@ -552,13 +505,6 @@ namespace System.Net.WebSockets
 
                 completedAsynchronouslyOrWithError = true;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this, completedAsynchronouslyOrWithError);
-                }
-            }
 
             return completedAsynchronouslyOrWithError;
         }
@@ -607,11 +553,6 @@ namespace System.Net.WebSockets
             // need to yield here to make sure that we don't get any exception synchronously
             await Task.Yield();
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-            }
-
             CancellationTokenRegistration cancellationTokenRegistration = default;
 
             try
@@ -648,11 +589,6 @@ namespace System.Net.WebSockets
             finally
             {
                 cancellationTokenRegistration.Dispose();
-
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Exit(this);
-                }
             }
         }
 
@@ -706,11 +642,6 @@ namespace System.Net.WebSockets
             WebSocketHttpListenerDuplexStream thisPtr = state as WebSocketHttpListenerDuplexStream;
             Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(state);
-            }
-
             try
             {
                 thisPtr._outputStream.SetClosedFlag();
@@ -720,11 +651,6 @@ namespace System.Net.WebSockets
 
             thisPtr._readTaskCompletionSource?.TrySetCanceled();
             thisPtr._writeTaskCompletionSource?.TrySetCanceled();
-
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Exit(state);
-            }
         }
 
         public void SwitchToOpaqueMode(WebSocketBase webSocket)
@@ -767,11 +693,6 @@ namespace System.Net.WebSockets
                 "'thisPtr.m_OutstandingOperations.m_Writes' MUST NOT be negative.");
 #endif
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(thisPtr);
-            }
-
             if (eventArgs.Exception != null)
             {
                 thisPtr._writeTaskCompletionSource.TrySetException(eventArgs.Exception);
@@ -780,11 +701,6 @@ namespace System.Net.WebSockets
             {
                 thisPtr._writeTaskCompletionSource.TrySetResult();
             }
-
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Exit(thisPtr);
-            }
         }
 
         private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs eventArgs)
@@ -797,11 +713,6 @@ namespace System.Net.WebSockets
                 "'thisPtr.m_OutstandingOperations.m_Reads' MUST NOT be negative.");
 #endif
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(thisPtr);
-            }
-
             if (eventArgs.Exception != null)
             {
                 thisPtr._readTaskCompletionSource.TrySetException(eventArgs.Exception);
@@ -810,11 +721,6 @@ namespace System.Net.WebSockets
             {
                 thisPtr._readTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred);
             }
-
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Exit(thisPtr);
-            }
         }
 
         internal class HttpListenerAsyncEventArgs : EventArgs, IDisposable
index 8cda459..8bf4128 100644 (file)
@@ -66,34 +66,17 @@ namespace System.Net.Mail
 
         public SmtpClient()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-            try
-            {
-                Initialize();
-            }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
+            Initialize();
         }
 
         public SmtpClient(string? host)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
-            try
-            {
-                _host = host;
-                Initialize();
-            }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
+            _host = host;
+            Initialize();
         }
 
         public SmtpClient(string? host, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host, port);
             try
             {
                 if (port < 0)
@@ -107,7 +90,6 @@ namespace System.Net.Mail
             }
             finally
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             }
         }
 
@@ -440,152 +422,144 @@ namespace System.Net.Mail
 
         public void Send(MailMessage message)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, message);
-
             if (_disposed)
             {
                 throw new ObjectDisposedException(GetType().FullName);
             }
-            try
+
+            if (NetEventSource.Log.IsEnabled())
             {
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
-                    NetEventSource.Associate(this, message);
-                }
+                NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
+                NetEventSource.Associate(this, message);
+            }
 
-                SmtpFailedRecipientException? recipientException = null;
+            SmtpFailedRecipientException? recipientException = null;
 
-                if (InCall)
-                {
-                    throw new InvalidOperationException(SR.net_inasync);
-                }
+            if (InCall)
+            {
+                throw new InvalidOperationException(SR.net_inasync);
+            }
 
-                if (message == null)
-                {
-                    throw new ArgumentNullException(nameof(message));
-                }
+            if (message == null)
+            {
+                throw new ArgumentNullException(nameof(message));
+            }
 
-                if (DeliveryMethod == SmtpDeliveryMethod.Network)
-                    CheckHostAndPort();
+            if (DeliveryMethod == SmtpDeliveryMethod.Network)
+                CheckHostAndPort();
 
-                MailAddressCollection recipients = new MailAddressCollection();
+            MailAddressCollection recipients = new MailAddressCollection();
 
-                if (message.From == null)
-                {
-                    throw new InvalidOperationException(SR.SmtpFromRequired);
-                }
+            if (message.From == null)
+            {
+                throw new InvalidOperationException(SR.SmtpFromRequired);
+            }
 
-                if (message.To != null)
-                {
-                    foreach (MailAddress address in message.To)
-                    {
-                        recipients.Add(address);
-                    }
-                }
-                if (message.Bcc != null)
+            if (message.To != null)
+            {
+                foreach (MailAddress address in message.To)
                 {
-                    foreach (MailAddress address in message.Bcc)
-                    {
-                        recipients.Add(address);
-                    }
+                    recipients.Add(address);
                 }
-                if (message.CC != null)
+            }
+            if (message.Bcc != null)
+            {
+                foreach (MailAddress address in message.Bcc)
                 {
-                    foreach (MailAddress address in message.CC)
-                    {
-                        recipients.Add(address);
-                    }
+                    recipients.Add(address);
                 }
-
-                if (recipients.Count == 0)
+            }
+            if (message.CC != null)
+            {
+                foreach (MailAddress address in message.CC)
                 {
-                    throw new InvalidOperationException(SR.SmtpRecipientRequired);
+                    recipients.Add(address);
                 }
+            }
 
-                _transport.IdentityRequired = false;  // everything completes on the same thread.
+            if (recipients.Count == 0)
+            {
+                throw new InvalidOperationException(SR.SmtpRecipientRequired);
+            }
 
-                try
-                {
-                    InCall = true;
-                    _timedOut = false;
-                    _timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
-                    bool allowUnicode = false;
-                    string? pickupDirectory = PickupDirectoryLocation;
-
-                    MailWriter writer;
-                    switch (DeliveryMethod)
-                    {
-                        case SmtpDeliveryMethod.PickupDirectoryFromIis:
-                            throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
+            _transport.IdentityRequired = false;  // everything completes on the same thread.
 
-                        case SmtpDeliveryMethod.SpecifiedPickupDirectory:
-                            if (EnableSsl)
-                            {
-                                throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
-                            }
+            try
+            {
+                InCall = true;
+                _timedOut = false;
+                _timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
+                bool allowUnicode = false;
+                string? pickupDirectory = PickupDirectoryLocation;
 
-                            allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
-                            ValidateUnicodeRequirement(message, recipients, allowUnicode);
-                            writer = GetFileMailWriter(pickupDirectory);
-                            break;
+                MailWriter writer;
+                switch (DeliveryMethod)
+                {
+                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
+                        throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
 
-                        case SmtpDeliveryMethod.Network:
-                        default:
-                            GetConnection();
-                            // Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
-                            allowUnicode = IsUnicodeSupported();
-                            ValidateUnicodeRequirement(message, recipients, allowUnicode);
-                            writer = _transport.SendMail(message.Sender ?? message.From, recipients,
-                                message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
-                            break;
-                    }
-                    _message = message;
-                    message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
-                    writer.Close();
+                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
+                        if (EnableSsl)
+                        {
+                            throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
+                        }
 
-                    //throw if we couldn't send to any of the recipients
-                    if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
-                    {
-                        throw recipientException;
-                    }
+                        allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
+                        ValidateUnicodeRequirement(message, recipients, allowUnicode);
+                        writer = GetFileMailWriter(pickupDirectory);
+                        break;
+
+                    case SmtpDeliveryMethod.Network:
+                    default:
+                        GetConnection();
+                        // Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
+                        allowUnicode = IsUnicodeSupported();
+                        ValidateUnicodeRequirement(message, recipients, allowUnicode);
+                        writer = _transport.SendMail(message.Sender ?? message.From, recipients,
+                            message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
+                        break;
                 }
-                catch (Exception e)
-                {
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
+                _message = message;
+                message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
+                writer.Close();
 
-                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
-                    {
-                        throw;
-                    }
-
-                    Abort();
-                    if (_timedOut)
-                    {
-                        throw new SmtpException(SR.net_timeout);
-                    }
+                //throw if we couldn't send to any of the recipients
+                if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
+                {
+                    throw recipientException;
+                }
+            }
+            catch (Exception e)
+            {
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
 
-                    if (e is SecurityException ||
-                        e is AuthenticationException ||
-                        e is SmtpException)
-                    {
-                        throw;
-                    }
+                if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
+                {
+                    throw;
+                }
 
-                    throw new SmtpException(SR.SmtpSendMailFailure, e);
+                Abort();
+                if (_timedOut)
+                {
+                    throw new SmtpException(SR.net_timeout);
                 }
-                finally
+
+                if (e is SecurityException ||
+                    e is AuthenticationException ||
+                    e is SmtpException)
                 {
-                    InCall = false;
-                    if (_timer != null)
-                    {
-                        _timer.Dispose();
-                    }
+                    throw;
                 }
+
+                throw new SmtpException(SR.SmtpSendMailFailure, e);
             }
             finally
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+                InCall = false;
+                if (_timer != null)
+                {
+                    _timer.Dispose();
+                }
             }
         }
 
@@ -605,7 +579,6 @@ namespace System.Net.Mail
                 throw new ObjectDisposedException(GetType().FullName);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, message, userToken, _transport);
 
             try
             {
@@ -656,83 +629,76 @@ namespace System.Net.Mail
                     throw new InvalidOperationException(SR.SmtpRecipientRequired);
                 }
 
-                try
+                InCall = true;
+                _cancelled = false;
+                _message = message;
+                string? pickupDirectory = PickupDirectoryLocation;
+
+                CredentialCache? cache;
+                // Skip token capturing if no credentials are used or they don't include a default one.
+                // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
+                _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
+
+                _asyncOp = AsyncOperationManager.CreateOperation(userToken);
+                switch (DeliveryMethod)
                 {
-                    InCall = true;
-                    _cancelled = false;
-                    _message = message;
-                    string? pickupDirectory = PickupDirectoryLocation;
-
-                    CredentialCache? cache;
-                    // Skip token capturing if no credentials are used or they don't include a default one.
-                    // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
-                    _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
-
-                    _asyncOp = AsyncOperationManager.CreateOperation(userToken);
-                    switch (DeliveryMethod)
-                    {
-                        case SmtpDeliveryMethod.PickupDirectoryFromIis:
-                            throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
+                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
+                        throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
 
-                        case SmtpDeliveryMethod.SpecifiedPickupDirectory:
+                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
+                        {
+                            if (EnableSsl)
                             {
-                                if (EnableSsl)
-                                {
-                                    throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
-                                }
-
-                                _writer = GetFileMailWriter(pickupDirectory);
-                                bool allowUnicode = IsUnicodeSupported();
-                                ValidateUnicodeRequirement(message, _recipients, allowUnicode);
-                                message.Send(_writer, true, allowUnicode);
-
-                                if (_writer != null)
-                                    _writer.Close();
-
-                                AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
-                                InCall = false;
-                                _asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
-                                break;
+                                throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
                             }
 
-                        case SmtpDeliveryMethod.Network:
-                        default:
-                            _operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
-                            lock (_operationCompletedResult.StartPostingAsyncOp())
-                            {
-                                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
-                                _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
-                                _operationCompletedResult.FinishPostingAsyncOp();
-                            }
+                            _writer = GetFileMailWriter(pickupDirectory);
+                            bool allowUnicode = IsUnicodeSupported();
+                            ValidateUnicodeRequirement(message, _recipients, allowUnicode);
+                            message.Send(_writer, true, allowUnicode);
+
+                            if (_writer != null)
+                                _writer.Close();
+
+                            AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
+                            InCall = false;
+                            _asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
                             break;
-                    }
-                }
-                catch (Exception e)
-                {
-                    InCall = false;
+                        }
 
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
+                    case SmtpDeliveryMethod.Network:
+                    default:
+                        _operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
+                        lock (_operationCompletedResult.StartPostingAsyncOp())
+                        {
+                            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
+                            _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
+                            _operationCompletedResult.FinishPostingAsyncOp();
+                        }
+                        break;
+                }
+            }
+            catch (Exception e)
+            {
+                InCall = false;
 
-                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
-                    {
-                        throw;
-                    }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
 
-                    Abort();
+                if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
+                {
+                    throw;
+                }
 
-                    if (e is SecurityException ||
-                        e is AuthenticationException ||
-                        e is SmtpException)
-                    {
-                        throw;
-                    }
+                Abort();
 
-                    throw new SmtpException(SR.SmtpSendMailFailure, e);
+                if (e is SecurityException ||
+                    e is AuthenticationException ||
+                    e is SmtpException)
+                {
+                    throw;
                 }
-            }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+
+                throw new SmtpException(SR.SmtpSendMailFailure, e);
             }
         }
 
@@ -757,22 +723,13 @@ namespace System.Net.Mail
                 throw new ObjectDisposedException(GetType().FullName);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
-            try
-            {
-                if (!InCall || _cancelled)
-                {
-                    return;
-                }
-
-                _cancelled = true;
-                Abort();
-            }
-            finally
+            if (!InCall || _cancelled)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
+                return;
             }
+
+            _cancelled = true;
+            Abort();
         }
 
 
@@ -901,7 +858,6 @@ namespace System.Net.Mail
         private void Complete(Exception? exception, IAsyncResult result)
         {
             ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState!;
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 if (_cancelled)
@@ -959,7 +915,6 @@ namespace System.Net.Mail
 
         private void SendMessageCallback(IAsyncResult result)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 _message!.EndSend(result);
@@ -970,16 +925,11 @@ namespace System.Net.Mail
             {
                 Complete(e, result);
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
 
         private void SendMailCallback(IAsyncResult result)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 _writer = _transport.EndSendMail(result);
@@ -993,7 +943,6 @@ namespace System.Net.Mail
             catch (Exception e)
             {
                 Complete(e, result);
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 return;
             }
 
@@ -1013,15 +962,10 @@ namespace System.Net.Mail
             {
                 Complete(e, result);
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
         private void ConnectCallback(IAsyncResult result)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 _transport.EndGetConnection(result);
@@ -1043,10 +987,6 @@ namespace System.Net.Mail
             {
                 Complete(e, result);
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
         // After we've estabilished a connection and initilized ServerSupportsEai,
index 431a4aa..f8e8aa5 100644 (file)
@@ -416,7 +416,6 @@ namespace System.Net.Mail
 
             internal void GetConnection()
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
                 if (_connection._isConnected)
                 {
                     throw new InvalidOperationException(SR.SmtpAlreadyConnected);
index 32192d1..ff3efc8 100644 (file)
@@ -16,42 +16,34 @@ namespace System.Net.Mail
 
         public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-            try
+            lock (_sessions)
             {
-                lock (_sessions)
+                NetworkCredential? cachedCredential;
+                if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
                 {
-                    NetworkCredential? cachedCredential;
-                    if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
+                    if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
                     {
-                        if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
-                        {
-                            return null;
-                        }
-
-                        _sessions[sessionCookie] = credential;
+                        return null;
+                    }
 
-                        string userName = credential.UserName;
-                        string domain = credential.Domain;
+                    _sessions[sessionCookie] = credential;
 
-                        if (domain != null && domain.Length > 0)
-                        {
-                            userName = domain + "\\" + userName;
-                        }
+                    string userName = credential.UserName;
+                    string domain = credential.Domain;
 
-                        return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName)), false);
-                    }
-                    else
+                    if (domain != null && domain.Length > 0)
                     {
-                        _sessions.Remove(sessionCookie);
-
-                        return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cachedCredential.Password)), true);
+                        userName = domain + "\\" + userName;
                     }
+
+                    return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName)), false);
+                }
+                else
+                {
+                    _sessions.Remove(sessionCookie);
+
+                    return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cachedCredential.Password)), true);
                 }
-            }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             }
         }
 
index 19af91e..eff8686 100644 (file)
@@ -17,7 +17,6 @@ namespace System.Net.Mail
 
         public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, "Authenticate");
             try
             {
                 lock (_sessions)
@@ -79,10 +78,6 @@ namespace System.Net.Mail
             {
                 return null;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "Authenticate");
-            }
         }
 
         public string AuthenticationType
index b6c6397..d5557af 100644 (file)
@@ -16,7 +16,6 @@ namespace System.Net.Mail
 
         public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, "Authenticate");
             try
             {
                 lock (_sessions)
@@ -53,10 +52,6 @@ namespace System.Net.Mail
             {
                 return null;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "Authenticate");
-            }
         }
 
         public string AuthenticationType
index f179604..2e427ec 100644 (file)
@@ -122,7 +122,6 @@ namespace System.Net.Mail
 
         internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback? callback, object? state, string host, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             IAsyncResult? result = null;
             try
             {
@@ -141,25 +140,14 @@ namespace System.Net.Mail
                 throw new SmtpException(SR.MailHostNotFound, innerException);
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Info(this, "Sync completion");
-                NetEventSource.Exit(this);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Sync completion");
+
             return result;
         }
 
         internal void EndGetConnection(IAsyncResult result)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-            try
-            {
-                _connection!.EndGetConnection(result);
-            }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
+            _connection!.EndGetConnection(result);
         }
 
         internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
index f23688a..54c6864 100644 (file)
@@ -24,7 +24,6 @@ namespace System.Net
 
         public static IPHostEntry GetHostEntry(IPAddress address)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (address is null)
@@ -40,13 +39,12 @@ namespace System.Net
 
             IPHostEntry ipHostEntry = GetHostEntryCore(address);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
             return ipHostEntry;
         }
 
         public static IPHostEntry GetHostEntry(string hostNameOrAddress)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (hostNameOrAddress is null)
@@ -71,7 +69,7 @@ namespace System.Net
                 ipHostEntry = GetHostEntryCore(hostNameOrAddress);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostNameOrAddress, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(hostNameOrAddress, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
             return ipHostEntry;
         }
 
@@ -79,9 +77,8 @@ namespace System.Net
         {
             if (NetEventSource.Log.IsEnabled())
             {
-                NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
                 Task<IPHostEntry> t = GetHostEntryCoreAsync(hostNameOrAddress, justReturnParsedIp: false, throwOnIIPAny: true);
-                t.ContinueWith((t, s) => NetEventSource.Exit((string)s!, $"{t.Result} with {((IPHostEntry)t.Result).AddressList.Length} entries"),
+                t.ContinueWith((t, s) => NetEventSource.Info((string)s!, $"{t.Result} with {((IPHostEntry)t.Result).AddressList.Length} entries"),
                     hostNameOrAddress, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
                 return t;
             }
@@ -93,8 +90,6 @@ namespace System.Net
 
         public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
-
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (address is null)
@@ -109,45 +104,23 @@ namespace System.Net
             }
 
             return RunAsync(s => {
-                    IPHostEntry ipHostEntry = GetHostEntryCore((IPAddress)s);
-                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit((IPAddress)s, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
-                    return ipHostEntry;
-                }, address);
-        }
-
-        public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback? requestCallback, object? stateObject)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
-
-            IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryAsync(address), requestCallback, stateObject);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, asyncResult);
-            return asyncResult;
-        }
-
-        public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback? requestCallback, object? stateObject)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
-
-            IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryAsync(hostNameOrAddress), requestCallback, stateObject);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, asyncResult);
-            return asyncResult;
+                IPHostEntry ipHostEntry = GetHostEntryCore((IPAddress)s);
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info((IPAddress)s, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+                return ipHostEntry;
+            }, address);
         }
 
-        public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(asyncResult, asyncResult);
+        public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback? requestCallback, object? stateObject) =>
+            TaskToApm.Begin(GetHostEntryAsync(address), requestCallback, stateObject);
 
-            IPHostEntry ipHostEntry = TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
+        public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback? requestCallback, object? stateObject) =>
+            TaskToApm.Begin(GetHostEntryAsync(hostNameOrAddress), requestCallback, stateObject);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries" );
-            return ipHostEntry;
-        }
+        public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) =>
+            TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
 
         public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (hostNameOrAddress is null)
@@ -172,32 +145,18 @@ namespace System.Net
                 addresses = GetHostAddressesCore(hostNameOrAddress);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostNameOrAddress, addresses);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(hostNameOrAddress, addresses);
             return addresses;
         }
 
         public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress) =>
             (Task<IPAddress[]>)GetHostEntryOrAddressesCoreAsync(hostNameOrAddress, justReturnParsedIp: true, throwOnIIPAny: true, justAddresses: true);
 
-        public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback? requestCallback, object? state)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
-
-            IAsyncResult asyncResult = TaskToApm.Begin(GetHostAddressesAsync(hostNameOrAddress), requestCallback, state);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostNameOrAddress, asyncResult);
-            return asyncResult;
-        }
-
-        public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(asyncResult, asyncResult);
-
-            IPAddress[] addresses = TaskToApm.End<IPAddress[]>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
+        public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback? requestCallback, object? state) =>
+            TaskToApm.Begin(GetHostAddressesAsync(hostNameOrAddress), requestCallback, state);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, addresses);
-            return addresses;
-        }
+        public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) =>
+            TaskToApm.End<IPAddress[]>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
 
         [Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
         public static IPHostEntry GetHostByName(string hostName)
@@ -218,31 +177,16 @@ namespace System.Net
         }
 
         [Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
-        public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback? requestCallback, object? stateObject)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostName, hostName);
-
-            IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: true, throwOnIIPAny: true), requestCallback, stateObject);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostName, asyncResult);
-            return asyncResult;
-        }
+        public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback? requestCallback, object? stateObject) =>
+            TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: true, throwOnIIPAny: true), requestCallback, stateObject);
 
         [Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
-        public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(asyncResult, asyncResult);
-
-            IPHostEntry ipHostEntry = TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(asyncResult, ipHostEntry);
-            return ipHostEntry;
-        }
+        public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult) =>
+            TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
 
         [Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
         public static IPHostEntry GetHostByAddress(string address)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (address is null)
@@ -252,14 +196,13 @@ namespace System.Net
 
             IPHostEntry ipHostEntry = GetHostEntryCore(IPAddress.Parse(address));
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, ipHostEntry);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry);
             return ipHostEntry;
         }
 
         [Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
         public static IPHostEntry GetHostByAddress(IPAddress address)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(address, address);
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (address is null)
@@ -269,14 +212,13 @@ namespace System.Net
 
             IPHostEntry ipHostEntry = GetHostEntryCore(address);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(address, ipHostEntry);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry);
             return ipHostEntry;
         }
 
         [Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
         public static IPHostEntry Resolve(string hostName)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(hostName, hostName);
             NameResolutionPal.EnsureSocketsAreInitialized();
 
             if (hostName is null)
@@ -304,25 +246,17 @@ namespace System.Net
                 ipHostEntry = GetHostEntryCore(hostName);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(hostName, ipHostEntry);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(hostName, ipHostEntry);
             return ipHostEntry;
         }
 
         [Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
-        public static IAsyncResult BeginResolve(string hostName, AsyncCallback? requestCallback, object? stateObject)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, hostName);
-
-            IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: false, throwOnIIPAny: false), requestCallback, stateObject);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, asyncResult);
-            return asyncResult;
-        }
+        public static IAsyncResult BeginResolve(string hostName, AsyncCallback? requestCallback, object? stateObject) =>
+            TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: false, throwOnIIPAny: false), requestCallback, stateObject);
 
         [Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
         public static IPHostEntry EndResolve(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, asyncResult);
             IPHostEntry ipHostEntry;
 
             try
@@ -345,7 +279,7 @@ namespace System.Net
                 ipHostEntry = CreateHostEntryForAddress(address);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, ipHostEntry);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, ipHostEntry);
             return ipHostEntry;
         }
 
index 5356aa3..c381399 100644 (file)
@@ -700,10 +700,7 @@ namespace System.Net
 
         internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCookieHeader, bool isThrow)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
 
             CookieCollection cookies = new CookieCollection();
             CookieVariant variant = CookieVariant.Unknown;
index 0e38295..ff3f6af 100644 (file)
@@ -163,8 +163,6 @@ namespace System.Net
                 throw new ArgumentNullException(nameof(authType));
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, uriPrefix, authType);
-
             if (_cache == null)
             {
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
@@ -218,8 +216,6 @@ namespace System.Net
                 throw new ArgumentOutOfRangeException(nameof(port));
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host, port, authenticationType);
-
             if (_cacheForHosts == null)
             {
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
index 472bd03..fdb1277 100644 (file)
@@ -14,7 +14,6 @@ namespace System.Net.Sockets
 
         internal SocketException(SocketError errorCode, uint platformError) : base((int)platformError)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, errorCode, platformError);
             _errorCode = errorCode;
         }
 
index e4af602..3e55404 100644 (file)
@@ -33,7 +33,6 @@ namespace System.Net.Sockets
         /// <summary>Creates a new instance of the <see cref='System.Net.Sockets.SocketException'/> class with the specified error code as SocketError.</summary>
         internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, socketError, Message);
             _errorCode = socketError;
         }
 
index 3064926..b95ba4b 100644 (file)
@@ -527,11 +527,7 @@ namespace System.Net
         //
         public override WebResponse GetResponse()
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
 
             try
             {
@@ -607,10 +603,6 @@ namespace System.Net
                 }
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, _ftpWebResponse);
-            }
             return _ftpWebResponse!;
         }
 
@@ -619,11 +611,7 @@ namespace System.Net
         /// </summary>
         public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
 
             ContextAwareResult? asyncResult;
 
@@ -689,10 +677,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
 
             return asyncResult;
         }
@@ -702,7 +686,6 @@ namespace System.Net
         /// </summary>
         public override WebResponse EndGetResponse(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             try
             {
                 // parameter validation
@@ -729,10 +712,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
 
             return _ftpWebResponse!;
         }
@@ -742,11 +721,7 @@ namespace System.Net
         /// </summary>
         public override Stream GetRequestStream()
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
 
             try
             {
@@ -790,10 +765,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
             return _stream;
         }
 
@@ -802,11 +773,7 @@ namespace System.Net
         /// </summary>
         public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
 
             ContextAwareResult? asyncResult = null;
             try
@@ -837,17 +804,12 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
 
             return asyncResult;
         }
 
         public override Stream EndGetRequestStream(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             Stream? requestStream = null;
             try
             {
@@ -885,10 +847,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
             return requestStream;
         }
 
@@ -1220,7 +1178,6 @@ namespace System.Net
         //
         private void SyncRequestCallback(object? obj)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, obj);
 
             RequestStage stageMode = RequestStage.CheckForError;
             try
@@ -1261,7 +1218,6 @@ namespace System.Net
             finally
             {
                 FinishRequestStage(stageMode);
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 CheckError(); //will throw on error
             }
         }
@@ -1271,7 +1227,6 @@ namespace System.Net
         //
         private void AsyncRequestCallback(object? obj)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, obj);
             RequestStage stageMode = RequestStage.CheckForError;
 
             try
@@ -1373,7 +1328,6 @@ namespace System.Net
             finally
             {
                 FinishRequestStage(stageMode);
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             }
         }
 
@@ -1502,7 +1456,6 @@ namespace System.Net
             if (_aborted)
                 return;
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
 
             try
             {
@@ -1535,10 +1488,6 @@ namespace System.Net
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
                 throw;
             }
-            finally
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            }
         }
 
         public bool KeepAlive
index fbe0389..fd0f63b 100644 (file)
@@ -23,8 +23,6 @@ namespace System.Net
 
         internal FtpWebResponse(Stream? responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string? statusLine, DateTime lastModified, string? bannerMessage, string? welcomeMessage, string? exitMessage)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, contentLength, statusLine);
-
             _responseStream = responseStream;
             if (responseStream == null && contentLength < 0)
             {
@@ -81,9 +79,7 @@ namespace System.Net
         /// </summary>
         public override void Close()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             _responseStream?.Close();
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         /// <summary>
index 97cb61d..c21afc9 100644 (file)
@@ -483,8 +483,6 @@ namespace System.Net
         /// </summary>
         private static void ThreadProc()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
-
             // Set this thread as a background thread.  On AppDomain/Process shutdown, the thread will just be killed.
             Thread.CurrentThread.IsBackground = true;
 
index e60897b..8f354be 100644 (file)
@@ -66,8 +66,6 @@ namespace System.Net
         //     Newly created WebRequest.
         private static WebRequest Create(Uri requestUri, bool useUriBase)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, requestUri);
-
             string LookupUri;
             WebRequestPrefixElement? Current = null;
             bool Found = false;
@@ -125,12 +123,10 @@ namespace System.Net
             {
                 // We found a match, so just call the creator and return what it does.
                 WebRequest webRequest = Current!.Creator.Create(requestUri);
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, webRequest);
                 return webRequest;
             }
 
             // Otherwise no match, throw an exception.
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null);
             throw new NotSupportedException(SR.net_unknown_prefix);
         }
 
index 087a70e..f1fef45 100644 (file)
@@ -78,8 +78,6 @@ namespace System.Net
                 return null;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(securityContext);
-
             SafeSslHandle sslContext = ((SafeDeleteSslContext)securityContext).SslContext;
 
             if (sslContext == null)
@@ -111,11 +109,7 @@ namespace System.Net
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Log.RemoteCertificate(result);
-                NetEventSource.Exit(securityContext, result);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result);
 
             return result;
         }
index c69851d..4b7d9e7 100644 (file)
@@ -52,8 +52,6 @@ namespace System.Net
                 return null;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(securityContext);
-
             X509Certificate2? result = null;
             SafeFreeCertContext? remoteContext = null;
             try
@@ -108,11 +106,7 @@ namespace System.Net
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Log.RemoteCertificate(result);
-                NetEventSource.Exit(securityContext, result);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result);
             return result;
         }
 
index 95fe84d..557b2e2 100644 (file)
@@ -96,8 +96,6 @@ namespace System.Net
                 return null;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(securityContext);
-
             X509Certificate2? result = null;
             SafeFreeCertContext? remoteContext = null;
             try
@@ -121,11 +119,7 @@ namespace System.Net
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Log.RemoteCertificate(result);
-                NetEventSource.Exit(null, result, securityContext);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result);
             return result;
         }
 
@@ -196,8 +190,6 @@ namespace System.Net
 
         private static unsafe uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(chainContext, cpp.dwFlags);
-
             Interop.Crypt32.CERT_CHAIN_POLICY_STATUS status = default;
             status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS);
 
index 17577c2..b0af716 100644 (file)
@@ -42,11 +42,7 @@ namespace System.Net.Security
 
         internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions, SslStream sslStream)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates);
-                NetEventSource.Log.SecureChannelCtor(this, sslStream, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SecureChannelCtor(this, sslStream, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy);
 
             SslStreamPal.VerifyPackageInfo();
 
@@ -58,9 +54,6 @@ namespace System.Net.Security
             _securityContext = null;
             _refreshCredentialNeeded = true;
             _sslAuthenticationOptions = sslAuthenticationOptions;
-
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this);
         }
 
         //
@@ -98,17 +91,12 @@ namespace System.Net.Security
 
         internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this, kind);
-
             ChannelBinding? result = null;
             if (_securityContext != null)
             {
                 result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
             }
 
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, result);
             return result;
         }
 
@@ -331,9 +319,6 @@ namespace System.Net.Security
 
         private bool AcquireClientCredentials(ref byte[]? thumbPrint)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             // Acquire possible Client Certificate information and set it on the handle.
             X509Certificate? clientCertificate = null;        // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
             List<X509Certificate>? filteredCerts = null;      // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
@@ -613,8 +598,6 @@ namespace System.Net.Security
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, cachedCred, _credentialsHandle);
             return cachedCred;
         }
 
@@ -625,9 +608,6 @@ namespace System.Net.Security
         //
         private bool AcquireServerCredentials(ref byte[]? thumbPrint)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             X509Certificate? localCertificate = null;
             X509Certificate2? selectedCert = null;
             bool cachedCred = false;
@@ -716,17 +696,12 @@ namespace System.Net.Security
                 thumbPrint = guessedThumbPrint;
             }
 
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, cachedCred, _credentialsHandle);
             return cachedCred;
         }
 
         //
         internal ProtocolToken NextMessage(ReadOnlySpan<byte> incomingBuffer)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             byte[]? nextmsg = null;
             SecurityStatusPal status = GenerateToken(incomingBuffer, ref nextmsg);
 
@@ -747,8 +722,6 @@ namespace System.Net.Security
                 {
                     NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException()!.Message}");
                 }
-
-                NetEventSource.Exit(this, token);
             }
             return token;
         }
@@ -770,8 +743,6 @@ namespace System.Net.Security
         --*/
         private SecurityStatusPal GenerateToken(ReadOnlySpan<byte> inputBuffer, ref byte[]? output)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}");
-
             byte[]? result = Array.Empty<byte>();
             SecurityStatusPal status = default;
             bool cachedCreds = false;
@@ -838,10 +809,6 @@ namespace System.Net.Security
             }
 
             output = result;
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Exit(this);
-            }
 
             return status;
         }
@@ -855,9 +822,6 @@ namespace System.Net.Security
         --*/
         internal void ProcessHandshakeSuccess()
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             if (_negotiatedApplicationProtocol == default)
             {
                 // try to get ALPN info unless we already have it. (renegotiation)
@@ -882,9 +846,6 @@ namespace System.Net.Security
             }
 
             SslStreamPal.QueryContextConnectionInfo(_securityContext!, out _connectionInfo);
-
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this);
         }
 
         /*++
@@ -901,11 +862,7 @@ namespace System.Net.Security
         --*/
         internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this, buffer, buffer.Length);
-                NetEventSource.DumpBuffer(this, buffer);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer);
 
             byte[] writeBuffer = output;
 
@@ -919,14 +876,11 @@ namespace System.Net.Security
 
             if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK)
             {
-                if (NetEventSource.Log.IsEnabled())
-                    NetEventSource.Exit(this, $"ERROR {secStatus}");
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ERROR {secStatus}");
             }
             else
             {
                 output = writeBuffer;
-                if (NetEventSource.Log.IsEnabled())
-                    NetEventSource.Exit(this, $"OK data size:{resultSize}");
             }
 
             return secStatus;
@@ -934,9 +888,6 @@ namespace System.Net.Security
 
         internal SecurityStatusPal Decrypt(byte[]? payload, ref int offset, ref int count)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this, payload, offset, count);
-
             if ((uint)offset > (uint)(payload == null ? 0 : payload.Length))
             {
                 NetEventSource.Fail(this, "Argument 'offset' out of range.");
@@ -962,9 +913,6 @@ namespace System.Net.Security
         //This method validates a remote certificate.
         internal bool VerifyRemoteCertificate(RemoteCertValidationCallback? remoteCertValidationCallback, ref ProtocolToken? alertToken)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
 
             // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
@@ -980,8 +928,7 @@ namespace System.Net.Security
 
                 if (remoteCertificateEx == null)
                 {
-                    if (NetEventSource.Log.IsEnabled())
-                        NetEventSource.Exit(this, $"No remote certificate received. RemoteCertRequired: {RemoteCertRequired}");
+                    if (NetEventSource.Log.IsEnabled() && RemoteCertRequired) NetEventSource.Error(this, $"Remote certificate required, but no remote certificate received");
                     sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
                 }
                 else
@@ -1063,17 +1010,11 @@ namespace System.Net.Security
                 remoteCertificateEx?.Dispose();
             }
 
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, success);
-
             return success;
         }
 
         public ProtocolToken? CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             TlsAlertMessage alertMessage;
 
             switch (sslPolicyErrors)
@@ -1109,17 +1050,11 @@ namespace System.Net.Security
                 return null;
             }
 
-            ProtocolToken token = GenerateAlertToken();
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, token);
-            return token;
+            return GenerateAlertToken();
         }
 
         public ProtocolToken? CreateShutdownToken()
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             SecurityStatusPal status;
             status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext!);
 
@@ -1136,10 +1071,7 @@ namespace System.Net.Security
                 return null;
             }
 
-            ProtocolToken token = GenerateAlertToken();
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, token);
-            return token;
+            return GenerateAlertToken();
         }
 
         private ProtocolToken GenerateAlertToken()
@@ -1149,9 +1081,7 @@ namespace System.Net.Security
             SecurityStatusPal status;
             status = GenerateToken(default, ref nextmsg);
 
-            ProtocolToken token = new ProtocolToken(nextmsg, status);
-
-            return token;
+            return new ProtocolToken(nextmsg, status);
         }
 
         private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain)
index 41ec03c..ea2c83e 100644 (file)
@@ -210,13 +210,13 @@ namespace System.Net.Security
                             if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Scavenged cache, New Cache Count = {s_cachedCreds.Count}");
                         }
                     }
-                    else if (NetEventSource.Log.IsEnabled())
+                    else
                     {
                         if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() (locked retry) Found already cached Handle = {cached.Target}");
                     }
                 }
             }
-            else if (NetEventSource.Log.IsEnabled())
+            else
             {
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() Ignoring incoming handle = {creds} since found already cached Handle = {cached.Target}");
             }
index 091bb57..9564416 100644 (file)
@@ -128,8 +128,6 @@ namespace System.Net.Security
         //
         private void CloseInternal()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             _exception = s_disposedSentinel;
             _context?.Close();
 
@@ -154,8 +152,6 @@ namespace System.Net.Security
                 // Suppress finalizer if the read buffer was returned.
                 GC.SuppressFinalize(this);
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private SecurityStatusPal EncryptData(ReadOnlyMemory<byte> buffer, ref byte[] outBuffer, out int outSize)
@@ -505,24 +501,15 @@ namespace System.Net.Security
         //
         private bool CompleteHandshake(ref ProtocolToken? alertToken)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this);
-
             _context!.ProcessHandshakeSuccess();
 
             if (!_context.VerifyRemoteCertificate(_sslAuthenticationOptions!.CertValidationDelegate, ref alertToken))
             {
                 _handshakeCompleted = false;
-
-                if (NetEventSource.Log.IsEnabled())
-                    NetEventSource.Exit(this, false);
                 return false;
             }
 
             _handshakeCompleted = true;
-
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, true);
             return true;
         }
 
@@ -1162,9 +1149,6 @@ namespace System.Net.Security
         // Returns TLS Frame size.
         private int GetFrameSize(ReadOnlySpan<byte> buffer)
         {
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Enter(this, buffer.Length);
-
             int payloadSize = -1;
             switch (_framing)
             {
@@ -1200,9 +1184,6 @@ namespace System.Net.Security
                     break;
             }
 
-            if (NetEventSource.Log.IsEnabled())
-                NetEventSource.Exit(this, payloadSize);
-
             return payloadSize;
         }
     }
index f44c0b6..3b305d3 100644 (file)
@@ -196,7 +196,6 @@ namespace System.Net.Sockets
         protected virtual void ForceReleaseUnmanagedStructures()
         {
             // Free the unmanaged memory if allocated.
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             _nativeOverlapped!.Dispose();
             _nativeOverlapped = null;
             GC.SuppressFinalize(this);
index 168af26..d6fa045 100644 (file)
@@ -739,8 +739,6 @@ namespace System.Net.Sockets
         private int _currentWriteTimeout = -1;
         internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, mode, timeout, silent);
-
             if (timeout < 0)
             {
                 timeout = 0; // -1 becomes 0 for the winsock stack
index 820a0eb..d20fbea 100644 (file)
@@ -19,8 +19,6 @@ namespace System.Net.Sockets
 
         public Socket(SocketInformation socketInformation)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             InitializeSockets();
 
             SocketError errorCode = SocketPal.CreateSocket(socketInformation, out _handle,
@@ -79,8 +77,6 @@ namespace System.Net.Sockets
                 _handle = null!;
                 throw new SocketException((int)errorCode);
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private unsafe void LoadSocketTypeFromHandle(
@@ -111,8 +107,6 @@ namespace System.Net.Sockets
 
         public SocketInformation DuplicateAndClose(int targetProcessId)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, targetProcessId);
-
             ThrowIfDisposed();
 
             SocketError errorCode = SocketPal.DuplicateSocket(_handle, targetProcessId, out SocketInformation info);
@@ -128,7 +122,6 @@ namespace System.Net.Sockets
 
             Close(timeout: -1);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return info;
         }
 
index 8b1d441..6bddfe3 100644 (file)
@@ -84,8 +84,7 @@ namespace System.Net.Sockets
         // Initializes a new instance of the Sockets.Socket class.
         public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addressFamily);
-
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, addressFamily);
             InitializeSockets();
 
             SocketError errorCode = SocketPal.CreateSocket(addressFamily, socketType, protocolType, out _handle);
@@ -103,7 +102,6 @@ namespace System.Net.Sockets
             _socketType = socketType;
             _protocolType = protocolType;
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         /// <summary>Initializes a new instance of the <see cref="Socket"/> class for the specified socket handle.</summary>
@@ -791,8 +789,7 @@ namespace System.Net.Sockets
         // Associates a socket with an end point.
         public void Bind(EndPoint localEP)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localEP);
-
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -805,8 +802,6 @@ namespace System.Net.Sockets
 
             Internals.SocketAddress socketAddress = Serialize(ref localEP);
             DoBind(localEP, socketAddress);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
@@ -866,10 +861,7 @@ namespace System.Net.Sockets
 
             ValidateBlockingMode();
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DST:{remoteEP}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DST:{remoteEP}");
 
             DnsEndPoint? dnsEP = remoteEP as DnsEndPoint;
             if (dnsEP != null)
@@ -900,8 +892,6 @@ namespace System.Net.Sockets
 
         public void Connect(IPAddress address, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
-
             ThrowIfDisposed();
 
             if (address == null)
@@ -928,13 +918,10 @@ namespace System.Net.Sockets
 
             IPEndPoint remoteEP = new IPEndPoint(address, port);
             Connect(remoteEP);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public void Connect(string host, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
-
             ThrowIfDisposed();
 
             if (host == null)
@@ -963,14 +950,10 @@ namespace System.Net.Sockets
                 IPAddress[] addresses = Dns.GetHostAddresses(host);
                 Connect(addresses, port);
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public void Connect(IPAddress[] addresses, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
-
             ThrowIfDisposed();
 
             if (addresses == null)
@@ -1022,26 +1005,16 @@ namespace System.Net.Sockets
             {
                 throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public void Close()
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"timeout = {_closeTimeout}");
-            }
-
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
             Dispose();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public void Close(int timeout)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, timeout);
             if (timeout < -1)
             {
                 throw new ArgumentOutOfRangeException(nameof(timeout));
@@ -1052,8 +1025,6 @@ namespace System.Net.Sockets
             if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
 
             Dispose();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, timeout);
         }
 
         /// <summary>
@@ -1070,7 +1041,7 @@ namespace System.Net.Sockets
         /// <param name="backlog">The maximum length of the pending connections queue.</param>
         public void Listen(int backlog)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, backlog);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, backlog);
             ThrowIfDisposed();
 
             // This may throw ObjectDisposedException.
@@ -1082,14 +1053,11 @@ namespace System.Net.Sockets
                 UpdateStatusAfterSocketErrorAndThrowException(errorCode);
             }
             _isListening = true;
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Creates a new Sockets.Socket instance to handle an incoming connection.
         public Socket Accept()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             // Validate input parameters.
 
             ThrowIfDisposed();
@@ -1136,11 +1104,7 @@ namespace System.Net.Sockets
             Debug.Assert(!acceptedSocketHandle.IsInvalid);
 
             Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
-                NetEventSource.Exit(this, socket);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
             return socket;
         }
 
@@ -1178,7 +1142,6 @@ namespace System.Net.Sockets
 
         public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             if (buffers == null)
@@ -1203,15 +1166,10 @@ namespace System.Net.Sockets
 
                 // Update the internal state of this socket according to the error before throwing.
                 UpdateStatusAfterSocketError(errorCode);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Error(this, new SocketException((int)errorCode));
-                    NetEventSource.Exit(this, 0);
-                }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
                 return 0;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -1229,8 +1187,6 @@ namespace System.Net.Sockets
 
         public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -1261,11 +1217,7 @@ namespace System.Net.Sockets
 
                 // Update the internal state of this socket according to the error before throwing.
                 UpdateStatusAfterSocketError(errorCode);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Error(this, new SocketException((int)errorCode));
-                    NetEventSource.Exit(this, 0);
-                }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
                 return 0;
             }
 
@@ -1273,7 +1225,6 @@ namespace System.Net.Sockets
             {
                 NetEventSource.Info(this, $"Send returns:{bytesTransferred}");
                 NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
-                NetEventSource.Exit(this, bytesTransferred);
             }
 
             return bytesTransferred;
@@ -1291,7 +1242,6 @@ namespace System.Net.Sockets
 
         public int Send(ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
             ValidateBlockingMode();
 
@@ -1307,7 +1257,6 @@ namespace System.Net.Sockets
                 bytesTransferred = 0;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -1318,8 +1267,6 @@ namespace System.Net.Sockets
 
         public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             if (!Connected)
@@ -1333,14 +1280,11 @@ namespace System.Net.Sockets
 
             SendFileInternal(fileName, preBuffer, postBuffer, flags);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Sends data to a specific end point, starting at the indicated location in the buffer.
         public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -1383,11 +1327,7 @@ namespace System.Net.Sockets
                 _rightEndPoint = remoteEP;
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.DumpBuffer(this, buffer, offset, size);
-                NetEventSource.Exit(this, bytesTransferred);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, size);
             return bytesTransferred;
         }
 
@@ -1437,7 +1377,6 @@ namespace System.Net.Sockets
 
         public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -1466,19 +1405,11 @@ namespace System.Net.Sockets
             {
                 // Update the internal state of this socket according to the error before throwing.
                 UpdateStatusAfterSocketError(errorCode);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Error(this, new SocketException((int)errorCode));
-                    NetEventSource.Exit(this, 0);
-                }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
                 return 0;
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
-                NetEventSource.Exit(this, bytesTransferred);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
 
             return bytesTransferred;
         }
@@ -1495,7 +1426,6 @@ namespace System.Net.Sockets
 
         public int Receive(Span<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
             ValidateBlockingMode();
 
@@ -1511,7 +1441,6 @@ namespace System.Net.Sockets
                 bytesTransferred = 0;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -1533,8 +1462,6 @@ namespace System.Net.Sockets
 
         public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             if (buffers == null)
@@ -1559,16 +1486,10 @@ namespace System.Net.Sockets
             {
                 // Update the internal state of this socket according to the error before throwing.
                 UpdateStatusAfterSocketError(errorCode);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Error(this, new SocketException((int)errorCode));
-                    NetEventSource.Exit(this, 0);
-                }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
                 return 0;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
-
             return bytesTransferred;
         }
 
@@ -1576,7 +1497,6 @@ namespace System.Net.Sockets
         // the end point.
         public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
             if (buffer == null)
             {
@@ -1653,7 +1573,6 @@ namespace System.Net.Sockets
         // the end point.
         public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -1735,11 +1654,7 @@ namespace System.Net.Sockets
                 throw socketException;
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.DumpBuffer(this, buffer, offset, size);
-                NetEventSource.Exit(this, bytesTransferred);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, size);
             return bytesTransferred;
         }
 
@@ -2105,7 +2020,6 @@ namespace System.Net.Sockets
         public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
             // Validate input parameters.
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, remoteEP);
             ThrowIfDisposed();
 
             if (remoteEP == null)
@@ -2176,7 +2090,6 @@ namespace System.Net.Sockets
 
         public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
             ThrowIfDisposed();
 
             if (host == null)
@@ -2205,9 +2118,7 @@ namespace System.Net.Sockets
             IPAddress? parsedAddress;
             if (IPAddress.TryParse(host, out parsedAddress))
             {
-                IAsyncResult r = BeginConnect(parsedAddress, port, requestCallback, state);
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, r);
-                return r;
+                return BeginConnect(parsedAddress, port, requestCallback, state);
             }
 
             ValidateForMultiConnect(isMultiEndpoint: true);
@@ -2228,13 +2139,11 @@ namespace System.Net.Sockets
             // Done posting.
             result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result);
             return result;
         }
 
         public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
             ThrowIfDisposed();
 
             if (address == null)
@@ -2258,14 +2167,11 @@ namespace System.Net.Sockets
                 throw new NotSupportedException(SR.net_invalidversion);
             }
 
-            IAsyncResult result = BeginConnect(new IPEndPoint(address, port), requestCallback, state);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result);
-            return result;
+            return BeginConnect(new IPEndPoint(address, port), requestCallback, state);
         }
 
         public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
             ThrowIfDisposed();
 
             if (addresses == null)
@@ -2310,13 +2216,11 @@ namespace System.Net.Sockets
             // Finished posting async op.  Possibly will call callback.
             result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, result);
             return result;
         }
 
         public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Start context-flowing op.  No need to lock - we don't use the context till the callback.
@@ -2333,7 +2237,6 @@ namespace System.Net.Sockets
 
         private void DoBeginDisconnect(bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             SocketError errorCode = SocketError.Success;
 
             errorCode = SocketPal.DisconnectAsync(this, _handle, reuseSocket, asyncResult);
@@ -2351,13 +2254,10 @@ namespace System.Net.Sockets
             {
                 throw new SocketException((int)errorCode);
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
         }
 
         public void Disconnect(bool reuseSocket)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             SocketError errorCode = SocketError.Success;
@@ -2374,8 +2274,6 @@ namespace System.Net.Sockets
 
             SetToDisconnected();
             _remoteEndPoint = null;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Routine Description:
@@ -2392,7 +2290,6 @@ namespace System.Net.Sockets
         //    int - Return code from async Connect, 0 for success, SocketError.NotConnected otherwise
         public void EndConnect(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2437,16 +2334,11 @@ namespace System.Net.Sockets
                 ExceptionDispatchInfo.Throw(ex);
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
-                NetEventSource.Exit(this, "");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
         }
 
         public void EndDisconnect(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
             ThrowIfDisposed();
 
             if (asyncResult == null)
@@ -2479,8 +2371,6 @@ namespace System.Net.Sockets
             {
                 UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Routine Description:
@@ -2513,7 +2403,6 @@ namespace System.Net.Sockets
 
         public IAsyncResult? BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2548,7 +2437,6 @@ namespace System.Net.Sockets
                 asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -2582,7 +2470,6 @@ namespace System.Net.Sockets
 
         public IAsyncResult? BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2612,7 +2499,6 @@ namespace System.Net.Sockets
                 asyncResult = null;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -2658,7 +2544,6 @@ namespace System.Net.Sockets
 
         public int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2689,15 +2574,10 @@ namespace System.Net.Sockets
                 UpdateSendSocketErrorForDisposed(ref errorCode);
                 // Update the internal state of this socket according to the error before throwing.
                 UpdateStatusAfterSocketError(errorCode);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Error(this, new SocketException((int)errorCode));
-                    NetEventSource.Exit(this, 0);
-                }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
                 return 0;
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -2708,8 +2588,6 @@ namespace System.Net.Sockets
 
         public IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             if (!Connected)
@@ -2719,16 +2597,11 @@ namespace System.Net.Sockets
 
             if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"::DoBeginSendFile() SRC:{LocalEndPoint} DST:{RemoteEndPoint} fileName:{fileName}");
 
-            IAsyncResult asyncResult = BeginSendFileInternal(fileName, preBuffer, postBuffer, flags, callback, state);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
-            return asyncResult;
+            return BeginSendFileInternal(fileName, preBuffer, postBuffer, flags, callback, state);
         }
 
         public void EndSendFile(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
             ThrowIfDisposed();
 
             if (asyncResult == null)
@@ -2737,8 +2610,6 @@ namespace System.Net.Sockets
             }
 
             EndSendFileInternal(asyncResult);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Routine Description:
@@ -2763,7 +2634,6 @@ namespace System.Net.Sockets
         //    IAsyncResult - Async result used to retrieve result
         public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2796,7 +2666,6 @@ namespace System.Net.Sockets
             // Finish, possibly posting the callback.  The callback won't be posted before this point is reached.
             asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -2853,8 +2722,6 @@ namespace System.Net.Sockets
         //    int - Number of bytes transferred
         public int EndSendTo(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2886,7 +2753,6 @@ namespace System.Net.Sockets
                 UpdateStatusAfterSocketErrorAndThrowException(errorCode);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -2925,8 +2791,6 @@ namespace System.Net.Sockets
 
         public IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -2961,7 +2825,6 @@ namespace System.Net.Sockets
                 asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -3002,8 +2865,6 @@ namespace System.Net.Sockets
 
         public IAsyncResult? BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -3035,7 +2896,6 @@ namespace System.Net.Sockets
                 asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -3096,8 +2956,6 @@ namespace System.Net.Sockets
 
         public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -3127,24 +2985,15 @@ namespace System.Net.Sockets
             {
                 // Update the internal state of this socket according to the error before throwing.
                 UpdateStatusAfterSocketError(errorCode);
-                if (NetEventSource.Log.IsEnabled())
-                {
-                    NetEventSource.Error(this, new SocketException((int)errorCode));
-                    NetEventSource.Exit(this, 0);
-                }
+                if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, new SocketException((int)errorCode));
                 return 0;
             }
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
         public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Enter(this);
-                NetEventSource.Info(this, $"size:{size}");
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"size:{size}");
 
             ThrowIfDisposed();
             if (buffer == null)
@@ -3248,17 +3097,12 @@ namespace System.Net.Sockets
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
-                NetEventSource.Exit(this, asyncResult);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
             return asyncResult;
         }
 
         public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
 
             ThrowIfDisposed();
             if (endPoint == null)
@@ -3316,7 +3160,6 @@ namespace System.Net.Sockets
             socketFlags = castedAsyncResult.SocketFlags;
             ipPacketInformation = castedAsyncResult.IPPacketInformation;
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -3346,8 +3189,6 @@ namespace System.Net.Sockets
         //    IAsyncResult - Async result used to retrieve result
         public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -3404,7 +3245,6 @@ namespace System.Net.Sockets
                 }
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -3465,8 +3305,6 @@ namespace System.Net.Sockets
         //    int - Number of bytes transferred
         public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -3521,7 +3359,6 @@ namespace System.Net.Sockets
             {
                 UpdateStatusAfterSocketErrorAndThrowException(errorCode);
             }
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, bytesTransferred);
             return bytesTransferred;
         }
 
@@ -3550,8 +3387,6 @@ namespace System.Net.Sockets
                 return BeginAccept(0, callback, state);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             Debug.Assert(Disposed);
             ThrowObjectDisposedException();
             return null; // unreachable
@@ -3565,7 +3400,6 @@ namespace System.Net.Sockets
         // This is the truly async version that uses AcceptEx.
         public IAsyncResult BeginAccept(Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -3584,7 +3418,6 @@ namespace System.Net.Sockets
             // Finish the flow capture, maybe complete here.
             asyncResult.FinishPostingAsyncOp(ref Caches.AcceptClosureCache);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, asyncResult);
             return asyncResult;
         }
 
@@ -3652,7 +3485,6 @@ namespace System.Net.Sockets
 
         public Socket EndAccept(out byte[]? buffer, out int bytesTransferred, IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
             ThrowIfDisposed();
 
             // Validate input parameters.
@@ -3684,18 +3516,13 @@ namespace System.Net.Sockets
                 UpdateStatusAfterSocketErrorAndThrowException(errorCode);
             }
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
-                NetEventSource.Exit(this, socket);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
             return socket;
         }
 
         // Disables sends and receives on a socket.
         public void Shutdown(SocketShutdown how)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, how);
             ThrowIfDisposed();
 
             if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"how:{how}");
@@ -3713,14 +3540,11 @@ namespace System.Net.Sockets
 
             SetToDisconnected();
             InternalSetBlocking(_willBlockInternal);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         #region Async methods
         public bool AcceptAsync(SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -3759,9 +3583,7 @@ namespace System.Net.Sockets
                 throw;
             }
 
-            bool pending = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
-            return pending;
+            return socketError == SocketError.IOPending;
         }
 
         public bool ConnectAsync(SocketAsyncEventArgs e) =>
@@ -3769,7 +3591,6 @@ namespace System.Net.Sockets
 
         private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
             bool pending;
 
             ThrowIfDisposed();
@@ -3877,13 +3698,11 @@ namespace System.Net.Sockets
                 pending = (socketError == SocketError.IOPending);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
             return pending;
         }
 
         public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null);
             bool pending;
 
             if (e == null)
@@ -3938,7 +3757,6 @@ namespace System.Net.Sockets
                 pending = attemptSocket.ConnectAsync(e, userSocket: false);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, pending);
             return pending;
         }
 
@@ -3956,8 +3774,6 @@ namespace System.Net.Sockets
 
         public bool DisconnectAsync(SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             // Throw if socket disposed
             ThrowIfDisposed();
 
@@ -3980,17 +3796,13 @@ namespace System.Net.Sockets
                 throw;
             }
 
-            bool retval = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, retval);
-            return retval;
+            return socketError == SocketError.IOPending;
         }
 
         public bool ReceiveAsync(SocketAsyncEventArgs e) => ReceiveAsync(e, default(CancellationToken));
 
         private bool ReceiveAsync(SocketAsyncEventArgs e, CancellationToken cancellationToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -4012,15 +3824,11 @@ namespace System.Net.Sockets
                 throw;
             }
 
-            bool pending = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
-            return pending;
+            return socketError == SocketError.IOPending;
         }
 
         public bool ReceiveFromAsync(SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -4063,14 +3871,11 @@ namespace System.Net.Sockets
             }
 
             bool pending = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
             return pending;
         }
 
         public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -4114,17 +3919,13 @@ namespace System.Net.Sockets
                 throw;
             }
 
-            bool pending = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
-            return pending;
+            return socketError == SocketError.IOPending;
         }
 
         public bool SendAsync(SocketAsyncEventArgs e) => SendAsync(e, default(CancellationToken));
 
         private bool SendAsync(SocketAsyncEventArgs e, CancellationToken cancellationToken)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -4146,15 +3947,11 @@ namespace System.Net.Sockets
                 throw;
             }
 
-            bool pending = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
-            return pending;
+            return socketError == SocketError.IOPending;
         }
 
         public bool SendPacketsAsync(SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -4184,15 +3981,11 @@ namespace System.Net.Sockets
                 throw;
             }
 
-            bool pending = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, pending);
-            return pending;
+            return socketError == SocketError.IOPending;
         }
 
         public bool SendToAsync(SocketAsyncEventArgs e)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, e);
-
             ThrowIfDisposed();
 
             if (e == null)
@@ -4235,9 +4028,7 @@ namespace System.Net.Sockets
                 _rightEndPoint = oldEndPoint;
             }
 
-            bool retval = (socketError == SocketError.IOPending);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, retval);
-            return retval;
+            return socketError == SocketError.IOPending;
         }
         #endregion
         #endregion
@@ -4330,8 +4121,6 @@ namespace System.Net.Sockets
 
         private void DoConnect(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, endPointSnapshot);
-
             SocketError errorCode = SocketPal.Connect(_handle, socketAddress.Buffer, socketAddress.Size);
 
             // Throw an appropriate SocketException if the native call fails.
@@ -4355,11 +4144,7 @@ namespace System.Net.Sockets
 
             // Update state and performance counters.
             SetToConnected();
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
-                NetEventSource.Exit(this);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
         }
 
         protected virtual void Dispose(bool disposing)
@@ -4369,7 +4154,6 @@ namespace System.Net.Sockets
                 try
                 {
                     NetEventSource.Info(this, $"disposing:{disposing} Disposed:{Disposed}");
-                    NetEventSource.Enter(this);
                 }
                 catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { }
             }
@@ -4377,7 +4161,6 @@ namespace System.Net.Sockets
             // Make sure we're the first call to Dispose
             if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 1)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 return;
             }
 
@@ -4483,14 +4266,9 @@ namespace System.Net.Sockets
 
         public void Dispose()
         {
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Info(this, $"timeout = {_closeTimeout}");
-                NetEventSource.Enter(this);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
             Dispose(true);
             GC.SuppressFinalize(this);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         ~Socket()
@@ -4501,7 +4279,6 @@ namespace System.Net.Sockets
         // This version does not throw.
         internal void InternalShutdown(SocketShutdown how)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"how:{how}");
 
             if (Disposed || _handle.IsInvalid)
             {
@@ -4548,8 +4325,6 @@ namespace System.Net.Sockets
 
         internal unsafe void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue, bool silent)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue} silent:{silent}");
-
             if (silent && (Disposed || _handle.IsInvalid))
             {
                 if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "skipping the call");
@@ -4682,11 +4457,8 @@ namespace System.Net.Sockets
         // error code, and will update internal state on success.
         private SocketError InternalSetBlocking(bool desired, out bool current)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, $"desired:{desired} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
-
             if (Disposed)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, "ObjectDisposed");
                 current = _willBlock;
                 return SocketError.Success;
             }
@@ -4729,8 +4501,6 @@ namespace System.Net.Sockets
         // Since this is private, the unsafe mode is specified with a flag instead of an overload.
         private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             EndPoint endPointSnapshot = remoteEP;
             Internals.SocketAddress socketAddress = Serialize(ref endPointSnapshot);
 
@@ -4784,11 +4554,7 @@ namespace System.Net.Sockets
             // This is a nop if the context isn't being flowed.
             asyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
 
-            if (NetEventSource.Log.IsEnabled())
-            {
-                NetEventSource.Info(this, $"{endPointSnapshot} returning AsyncResult:{asyncResult}");
-                NetEventSource.Exit(this, asyncResult);
-            }
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{endPointSnapshot} returning AsyncResult:{asyncResult}");
             return asyncResult;
         }
 
@@ -5039,8 +4805,6 @@ namespace System.Net.Sockets
 
         internal void SetToDisconnected()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (!_isConnected)
             {
                 // Socket was already disconnected.
@@ -5079,7 +4843,6 @@ namespace System.Net.Sockets
         {
             // If we already know the socket is disconnected
             // we don't need to do anything else.
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
             if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"errorCode:{errorCode}");
 
             if (_isConnected && (_handle.IsInvalid || (errorCode != SocketError.WouldBlock &&
index 0813c26..e70b162 100644 (file)
@@ -30,7 +30,7 @@ namespace System.Net.Sockets
         // Initializes a new instance of the System.Net.Sockets.TcpClient class.
         public TcpClient(AddressFamily family)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, family);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, family);
 
             // Validate parameter
             if (family != AddressFamily.InterNetwork &&
@@ -42,14 +42,12 @@ namespace System.Net.Sockets
 
             _family = family;
             InitializeClientSocket();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point.
         public TcpClient(IPEndPoint localEP)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localEP);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
 
             if (localEP == null)
             {
@@ -59,15 +57,13 @@ namespace System.Net.Sockets
             _family = localEP.AddressFamily; // set before calling CreateSocket
             InitializeClientSocket();
             _clientSocket.Bind(localEP);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on
         // the specified host.
         public TcpClient(string hostname, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, hostname);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, hostname);
 
             if (hostname == null)
             {
@@ -87,19 +83,13 @@ namespace System.Net.Sockets
                 _clientSocket?.Close();
                 throw;
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Used by TcpListener.Accept().
         internal TcpClient(Socket acceptedSocket)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, acceptedSocket);
-
             _clientSocket = acceptedSocket;
             _active = true;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Used by the class to indicate that a connection has been made.
@@ -139,7 +129,6 @@ namespace System.Net.Sockets
         // Connects the Client to the specified port on the specified host.
         public void Connect(string hostname, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, hostname);
 
             ThrowIfDisposed();
 
@@ -228,15 +217,11 @@ namespace System.Net.Sockets
                     throw new SocketException((int)SocketError.NotConnected);
                 }
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Connects the Client to the specified port on the specified host.
         public void Connect(IPAddress address, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
-
             ThrowIfDisposed();
 
             if (address == null)
@@ -250,15 +235,11 @@ namespace System.Net.Sockets
 
             IPEndPoint remoteEP = new IPEndPoint(address, port);
             Connect(remoteEP);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Connect the Client to the specified end point.
         public void Connect(IPEndPoint remoteEP)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, remoteEP);
-
             ThrowIfDisposed();
 
             if (remoteEP == null)
@@ -269,50 +250,28 @@ namespace System.Net.Sockets
             Client.Connect(remoteEP);
             _family = Client.AddressFamily;
             _active = true;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public void Connect(IPAddress[] ipAddresses, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, ipAddresses);
-
             Client.Connect(ipAddresses, port);
             _family = Client.AddressFamily;
             _active = true;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public Task ConnectAsync(IPAddress address, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
 
             Task result = CompleteConnectAsync(Client.ConnectAsync(address, port));
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return result;
-        }
-
-        public Task ConnectAsync(string host, int port)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, host);
-
-            Task result = CompleteConnectAsync(Client.ConnectAsync(host, port));
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
             return result;
         }
 
-        public Task ConnectAsync(IPAddress[] addresses, int port)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
+        public Task ConnectAsync(string host, int port) =>
+            CompleteConnectAsync(Client.ConnectAsync(host, port));
 
-            Task result = CompleteConnectAsync(Client.ConnectAsync(addresses, port));
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return result;
-        }
+        public Task ConnectAsync(IPAddress[] addresses, int port) =>
+            CompleteConnectAsync(Client.ConnectAsync(addresses, port));
 
         private async Task CompleteConnectAsync(Task task)
         {
@@ -320,51 +279,25 @@ namespace System.Net.Sockets
             _active = true;
         }
 
-        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, address);
-
-            IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return result;
-        }
-
-        public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, (string)host);
-
-            IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return result;
-        }
-
-        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
-        {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, addresses);
+        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state) =>
+            Client.BeginConnect(address, port, requestCallback, state);
 
-            IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state);
+        public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state) =>
+            Client.BeginConnect(host, port, requestCallback, state);
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return result;
-        }
+        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state) =>
+            Client.BeginConnect(addresses, port, requestCallback, state);
 
         public void EndConnect(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, asyncResult);
-
             _clientSocket.EndConnect(asyncResult);
             _active = true;
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Returns the stream used to read and write data to the remote host.
         public NetworkStream GetStream()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             ThrowIfDisposed();
 
             if (!Connected)
@@ -377,7 +310,6 @@ namespace System.Net.Sockets
                 _dataStream = new NetworkStream(Client, true);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, _dataStream);
             return _dataStream;
         }
 
@@ -386,8 +318,6 @@ namespace System.Net.Sockets
         // Disposes the Tcp connection.
         protected virtual void Dispose(bool disposing)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
             {
                 if (disposing)
@@ -420,8 +350,6 @@ namespace System.Net.Sockets
                     GC.SuppressFinalize(this);
                 }
             }
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         public void Dispose() => Dispose(true);
index e875434..d11d283 100644 (file)
@@ -19,21 +19,22 @@ namespace System.Net.Sockets
         // Initializes a new instance of the TcpListener class with the specified local end point.
         public TcpListener(IPEndPoint localEP)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localEP);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
+
             if (localEP == null)
             {
                 throw new ArgumentNullException(nameof(localEP));
             }
             _serverSocketEP = localEP;
             _serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Initializes a new instance of the TcpListener class that listens to the specified IP address
         // and port.
         public TcpListener(IPAddress localaddr, int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this, localaddr);
+            if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localaddr);
+
             if (localaddr == null)
             {
                 throw new ArgumentNullException(nameof(localaddr));
@@ -45,7 +46,6 @@ namespace System.Net.Sockets
 
             _serverSocketEP = new IPEndPoint(localaddr, port);
             _serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Initiailizes a new instance of the TcpListener class that listens on the specified port.
@@ -141,12 +141,9 @@ namespace System.Net.Sockets
                 throw new ArgumentOutOfRangeException(nameof(backlog));
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             // Already listening.
             if (_active)
             {
-                if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
                 return;
             }
 
@@ -165,19 +162,14 @@ namespace System.Net.Sockets
             }
 
             _active = true;
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Closes the network connection.
         public void Stop()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             _serverSocket?.Dispose();
             _active = false;
             _serverSocket = null;
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
         }
 
         // Determine if there are pending connection requests.
@@ -194,54 +186,38 @@ namespace System.Net.Sockets
         // Accept the first pending connection
         public Socket AcceptSocket()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (!_active)
             {
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            Socket socket = _serverSocket!.Accept();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, socket);
-            return socket;
+            return _serverSocket!.Accept();
         }
 
         public TcpClient AcceptTcpClient()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (!_active)
             {
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
             Socket acceptedSocket = _serverSocket!.Accept();
-            TcpClient returnValue = new TcpClient(acceptedSocket);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, returnValue);
-            return returnValue;
+            return new TcpClient(acceptedSocket);
         }
 
         public IAsyncResult BeginAcceptSocket(AsyncCallback? callback, object? state)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
 
             if (!_active)
             {
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            IAsyncResult result = _serverSocket!.BeginAccept(callback, state);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-            return result;
+            return _serverSocket!.BeginAccept(callback, state);
         }
 
         public Socket EndAcceptSocket(IAsyncResult asyncResult)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (asyncResult == null)
             {
                 throw new ArgumentNullException(nameof(asyncResult));
@@ -255,10 +231,7 @@ namespace System.Net.Sockets
             }
 
             // This will throw ObjectDisposedException if Stop() has been called.
-            Socket socket = asyncSocket.EndAccept(asyncResult);
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this, socket);
-            return socket;
+            return asyncSocket.EndAccept(asyncResult);
         }
 
         public IAsyncResult BeginAcceptTcpClient(AsyncCallback? callback, object? state) =>
@@ -269,18 +242,12 @@ namespace System.Net.Sockets
 
         public Task<Socket> AcceptSocketAsync()
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(this);
-
             if (!_active)
             {
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            Task<Socket> result = _serverSocket!.AcceptAsync();
-
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(this);
-
-            return result;
+            return _serverSocket!.AcceptAsync();
         }
 
         public Task<TcpClient> AcceptTcpClientAsync()
@@ -295,8 +262,6 @@ namespace System.Net.Sockets
         // This creates a TcpListener that listens on both IPv4 and IPv6 on the given port.
         public static TcpListener Create(int port)
         {
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(null, port);
-
             if (!TcpValidationHelpers.ValidatePortNumber(port))
             {
                 throw new ArgumentOutOfRangeException(nameof(port));
@@ -315,8 +280,6 @@ namespace System.Net.Sockets
                 listener = new TcpListener(IPAddress.Any, port);
             }
 
-            if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(null, port);
-
             return listener;
         }