Skip to content

Instantly share code, notes, and snippets.

@nick-beer
Last active January 21, 2023 14:12
Show Gist options
  • Save nick-beer/b76f536f513556e5b5246762c57e2a94 to your computer and use it in GitHub Desktop.
Save nick-beer/b76f536f513556e5b5246762c57e2a94 to your computer and use it in GitHub Desktop.
Simple/Demonstration extension method to provide async/await on top of IVI VISA IMessageBasedRawIO Read APIs
namespace Ivi.Visa;
public static class RawIOReadExtensions
{
public static async ValueTask ReadAsync(
this IMessageBasedRawIO io,
byte[] buffer,
long index = 0,
long count = -1,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
TaskCompletionSource completionSource = new();
var asyncResult = io.BeginRead(buffer, index, count, OnReadComplete, null);
var canBeCanceled = cancellationToken.CanBeCanceled && !asyncResult.CompletedSynchronously;
using CancellationTokenRegistration registration = canBeCanceled
? cancellationToken.Register(() => io.AbortAsyncOperation(asyncResult))
: default;
await completionSource.Task;
void OnReadComplete(IVisaAsyncResult result)
{
io.EndRead(result);
if (result.IsAborted)
{
completionSource.SetCanceled(cancellationToken);
}
else
{
completionSource.SetResult();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment