Skip to content

Instantly share code, notes, and snippets.

@veton
Created May 17, 2020 07:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veton/4d9534fdfd0c592105f6bd616643546e to your computer and use it in GitHub Desktop.
Save veton/4d9534fdfd0c592105f6bd616643546e to your computer and use it in GitHub Desktop.
using System.Threading;
using System.Threading.Tasks;
using Generic = System.Collections.Generic;
using Fabric = Microsoft.ServiceFabric.Data;
public static class FabricAsyncEnumerableExtensions
{
/// <summary>
/// Converts ServiceFabric <see cref="Microsoft.ServiceFabric.Data.IAsyncEnumerable"/> to dotnet native <see cref="System.Collections.Generic.IAsyncEnumerable"/>.
/// </summary>
public static Generic.IAsyncEnumerable<T> ToGeneric<T>(this Fabric.IAsyncEnumerable<T> source) =>
new AsyncEnumerableWrapper<T>(source);
private class AsyncEnumerableWrapper<T> : Generic.IAsyncEnumerable<T>
{
private readonly Fabric.IAsyncEnumerable<T> _source;
public AsyncEnumerableWrapper(Fabric.IAsyncEnumerable<T> source) => _source = source;
public Generic.IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken _ = default)
{
Fabric.IAsyncEnumerator<T> enumerator = _source.GetAsyncEnumerator();
return new AsyncEnumeratorWrapper<T>(enumerator);
}
}
private class AsyncEnumeratorWrapper<T> : Generic.IAsyncEnumerator<T>
{
private readonly Fabric.IAsyncEnumerator<T> _source;
public AsyncEnumeratorWrapper(Fabric.IAsyncEnumerator<T> source) => _source = source;
public async ValueTask DisposeAsync() =>
await Task.Run(_source.Dispose).ConfigureAwait(false);
public async ValueTask<bool> MoveNextAsync() =>
await _source.MoveNextAsync(default).ConfigureAwait(false);
public T Current => _source.Current;
}
}
public async Task<IEnumerable<Product>> GetAllProductsAsync()
{
IReliableDictionary<Guid, Product> reliableDictionary =
await _stateManager.GetOrAddAsync<IReliableDictionary<Guid, Product>>("products").ConfigureAwait(false);
using ITransaction tx = _stateManager.CreateTransaction();
Fabric.IAsyncEnumerable<KeyValuePair<Guid, Product>> productsAsync =
await reliableDictionary.CreateEnumerableAsync(tx).ConfigureAwait(false);
return await productsAsync.ToGeneric()
.Select(p => p.Value)
.ToListAsync()
.ConfigureAwait(false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment