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

Implements SslStreamProxy write synchronization with SemaphoreSlim #1

Open
wants to merge 1 commit into
base: WriteAsyncCollision
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -104,21 +104,33 @@ internal enum SNISMUXFlags

internal class SslStreamProxy : SslStream
{
private Task _currentTask;
private readonly SemaphoreSlim _semaphore;

public SslStreamProxy(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
public SslStreamProxy(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
: base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback)
{ }
{
_semaphore = new SemaphoreSlim(1); /* granting one concurrent write on innerStream */
}

// Prevent the WriteAsync's collision
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (_currentTask != null && _currentTask.Status != TaskStatus.RanToCompletion)
await _semaphore.WaitAsync(cancellationToken);
try
{
_currentTask.Wait(cancellationToken);
await base.WriteAsync(buffer, offset, count, cancellationToken);
}
_currentTask = base.WriteAsync(buffer, offset, count, cancellationToken);
return _currentTask;
finally
{
_semaphore.Release();
}
return;
}

protected override void Dispose(bool disposing)
{
_semaphore?.Dispose();
base.Dispose(disposing);
}
}

Expand Down