Skip to content

Instantly share code, notes, and snippets.

@gacardinal
Last active January 9, 2020 18:27
Show Gist options
  • Save gacardinal/18e7c01717b5720cb9ef7b3c0578db5b to your computer and use it in GitHub Desktop.
Save gacardinal/18e7c01717b5720cb9ef7b3c0578db5b to your computer and use it in GitHub Desktop.
C#.NET Socket Task Extension for DisconnectAsync
namespace DisconnectAsyncTaskExtension
{
static class DisconnectAsyncTaskExtension
{
public static Task<SocketAsyncEventArgs> DisconnectAsyncTask(this Socket that, SocketAsyncEventArgs disconnectArgs)
{
TaskCompletionSource<SocketAsyncEventArgs> tcs = new TaskCompletionSource<SocketAsyncEventArgs>();
disconnectArgs.Completed += (object sender, SocketAsyncEventArgs completedArgs) => {
try
{
tcs.SetResult(completedArgs);
}
catch (Exception e) { tcs.TrySetException(e); }
};
try
{
bool isIOPending = that.DisconnectAsync(disconnectArgs);
if (!isIOPending)
{
tcs.SetResult(disconnectArgs);
}
}
catch (Exception e) { tcs.TrySetException(e); }
return tcs.Task;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment