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

Improve serial read/receive operations #270

Merged
merged 1 commit into from
Nov 24, 2020
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class Controller : IControllerLocal
{
private ushort lastOutboundMessage;
private readonly Semaphore _sendSemaphore = new Semaphore(1, 1);
private readonly Semaphore _receiveSemaphore = new Semaphore(1, 1);
private readonly int nextEndpointId;
private readonly object incrementLock = new object();

Expand Down Expand Up @@ -46,7 +47,10 @@ private void ProcessExit()

public async Task<bool> SendAsync(MessageRaw raw, CancellationToken cancellationToken)
{
_sendSemaphore.WaitOne();
if(!_sendSemaphore.WaitOne())
{
return false;
}

// check for cancellation request
if (cancellationToken.IsCancellationRequested)
Expand Down Expand Up @@ -149,6 +153,11 @@ private async Task<uint> SendRawBufferAsync(byte[] buffer, TimeSpan waiTimeout,

internal async Task<int> ReadBufferAsync(byte[] buffer, int offset, int bytesToRead, TimeSpan waitTimeout, CancellationToken cancellationToken)
{
if (!_receiveSemaphore.WaitOne())
{
return 0;
}

// check for cancellation request
if (cancellationToken.IsCancellationRequested)
{
Expand Down Expand Up @@ -194,6 +203,10 @@ internal async Task<int> ReadBufferAsync(byte[] buffer, int offset, int bytesToR
// catch everything else, doesn't matter
return 0;
}
finally
{
_receiveSemaphore.Release();
}

return bytesToReadRequested - bytesToRead;
}
Expand Down