Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft] Idea for detection of synchronous completions for APM over Task in sockets #51693

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ internal static class TaskToApm
public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state) =>
new TaskAsyncResult(task, state, callback);

public static Task GetSynchronousExceptionTask(Exception ex) => new FailedSynchronouslyCompletionSource(ex).Task;

public static Task<T> GetSynchronousExceptionTask<T>(Exception ex) => new FailedSynchronouslyCompletionSource<T>(ex).Task;

public static ValueTask<T> GetSynchronousExceptionValueTask<T>(Exception ex) => new ValueTask<T>(new FailedSynchronouslyCompletionSource<T>(ex).Task);

public static bool FailedSynchronously(this Task task) => task.IsFaulted && task.AsyncState is Exception;

public static void ThrowIfFailedSynchronously(this Task task)
{
if (task.IsFaulted && task.AsyncState is Exception ex)
{
throw ex;
}
}

/// <summary>Processes an IAsyncResult returned by Begin.</summary>
/// <param name="asyncResult">The IAsyncResult to unwrap.</param>
public static void End(IAsyncResult asyncResult)
Expand Down Expand Up @@ -68,6 +84,22 @@ private static void ThrowArgumentException(IAsyncResult asyncResult) =>
new ArgumentNullException(nameof(asyncResult)) :
new ArgumentException(null, nameof(asyncResult)));

private sealed class FailedSynchronouslyCompletionSource : TaskCompletionSource
{
public FailedSynchronouslyCompletionSource(Exception exception) : base(exception)
{
SetException(exception);
}
}

private sealed class FailedSynchronouslyCompletionSource<T> : TaskCompletionSource<T>
{
public FailedSynchronouslyCompletionSource(Exception exception) : base(exception)
{
SetException(exception);
}
}

/// <summary>Provides a simple IAsyncResult that wraps a Task.</summary>
/// <remarks>
/// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
<Compile Include="System\Net\Sockets\TransmitFileOptions.cs" />
<Compile Include="System\Net\Sockets\UDPClient.cs" />
<Compile Include="System\Net\Sockets\UdpReceiveResult.cs" />
<Compile Include="System\Net\Sockets\AcceptOverlappedAsyncResult.cs" />
<Compile Include="System\Net\Sockets\BaseOverlappedAsyncResult.cs" />
<Compile Include="System\Net\Sockets\DisconnectOverlappedAsyncResult.cs" />
<Compile Include="System\Net\Sockets\UnixDomainSocketEndPoint.cs" />
Expand Down Expand Up @@ -90,7 +89,6 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)' == 'true'">
<!-- Windows: CoreCLR -->
<Compile Include="System\Net\Sockets\AcceptOverlappedAsyncResult.Windows.cs" />
<Compile Include="System\Net\Sockets\BaseOverlappedAsyncResult.Windows.cs" />
<Compile Include="System\Net\Sockets\DynamicWinsockMethods.cs" />
<Compile Include="System\Net\Sockets\SafeSocketHandle.Windows.cs" />
Expand Down Expand Up @@ -185,7 +183,6 @@
Link="Common\System\Net\CompletionPortHelper.Windows.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
<Compile Include="System\Net\Sockets\AcceptOverlappedAsyncResult.Unix.cs" />
<Compile Include="System\Net\Sockets\BaseOverlappedAsyncResult.Unix.cs" />
<Compile Include="System\Net\Sockets\DisconnectOverlappedAsyncResult.Unix.cs" />
<Compile Include="System\Net\Sockets\SafeSocketHandle.Unix.cs" />
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@ public Task<Socket> AcceptAsync(Socket? acceptSocket)
{
// The operation completed synchronously. Get a task for it.
t = saea.SocketError == SocketError.Success ?
Task.FromResult(saea.AcceptSocket!) :
Task.FromException<Socket>(GetException(saea.SocketError));
Task.FromResult(saea.AcceptSocket!) : TaskToApm.GetSynchronousExceptionTask<Socket>(GetException(saea.SocketError));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note this is making the failure path more expensive for everyone, not just code using the APM methods.


// There won't be a callback, and we're done with the SAEA, so return it to the pool.
ReturnSocketAsyncEventArgs(saea);
Expand Down Expand Up @@ -959,8 +958,7 @@ public ValueTask<int> SendAsync(Socket socket, CancellationToken cancellationTok
Release();

return error == SocketError.Success ?
new ValueTask<int>(bytesTransferred) :
ValueTask.FromException<int>(CreateException(error));
new ValueTask<int>(bytesTransferred) : TaskToApm.GetSynchronousExceptionValueTask<int>(CreateException(error));
}

public ValueTask SendAsyncForNetworkStream(Socket socket, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,6 @@ public SocketInformation DuplicateAndClose(int targetProcessId)
throw new PlatformNotSupportedException(SR.net_sockets_duplicateandclose_notsupported);
}

public IAsyncResult BeginAccept(int receiveSize, AsyncCallback? callback, object? state)
{
throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_apm_notsupported);
}

public IAsyncResult BeginAccept(Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state)
{
throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_apm_notsupported);
}

public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
{
throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_apm_notsupported);
}

public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
{
throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_apm_notsupported);
}

internal bool PreferInlineCompletions
{
get => _handle.PreferInlineCompletions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Versioning;

namespace System.Net.Sockets
Expand Down Expand Up @@ -145,30 +146,6 @@ public SocketInformation DuplicateAndClose(int targetProcessId)
return info;
}

public IAsyncResult BeginAccept(int receiveSize, AsyncCallback? callback, object? state)
{
return BeginAccept(acceptSocket: null, receiveSize, callback, state);
}

// This is the truly async version that uses AcceptEx.
public IAsyncResult BeginAccept(Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state)
{
return BeginAcceptCommon(acceptSocket, receiveSize, callback, state);
}

public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
{
Socket socket = EndAccept(out byte[] innerBuffer, out int bytesTransferred, asyncResult);
buffer = new byte[bytesTransferred];
Buffer.BlockCopy(innerBuffer, 0, buffer, 0, bytesTransferred);
return socket;
}

public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
{
return EndAcceptCommon(out buffer!, out bytesTransferred, asyncResult);
}

private DynamicWinsockMethods GetDynamicWinsockMethods()
{
return _dynamicWinsockMethods ??= DynamicWinsockMethods.GetMethods(_addressFamily, _socketType, _protocolType);
Expand Down
Loading