Last active
January 21, 2023 14:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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