using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using ZeroDDS.Core;
using ZeroDDS.Pub;
using ZeroDDS.Sub;
namespace ZeroDDS.Sub;
public static class DataReaderAsyncExtensions
{
public static Task<bool> WaitForDataAsync<T>(this DataReader<T> reader,
TimeSpan timeout, CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var duration = ZeroDDS.TimeSpanBridge.ToDuration(timeout);
return Task.Run(() => reader.WaitForData(duration, ct), ct);
}
public static async IAsyncEnumerable<Sample<T>> TakeAsync<T>(this DataReader<T> reader,
TimeSpan timeout, [EnumeratorCancellation] CancellationToken ct = default)
{
bool ready = await reader.WaitForDataAsync(timeout, ct).ConfigureAwait(false);
if (!ready) yield break;
var samples = reader.Take();
foreach (var s in samples)
{
ct.ThrowIfCancellationRequested();
yield return s;
}
}
public static IAsyncEnumerable<Sample<T>> TakeAsync<T>(this DataReader<T> reader,
CancellationToken ct = default) =>
reader.TakeAsync(System.Threading.Timeout.InfiniteTimeSpan, ct);
}
public static class DataWriterAsyncExtensions
{
public static Task WriteAsync<T>(this DataWriter<T> writer, T sample,
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
try
{
writer.Write(sample);
return Task.CompletedTask;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
}