public ValueTask DisposeAsync()
                {
                    _enumerator?.DisposeAsync();
                    _enumerator = null;

                    return default;
                }
Exemplo n.º 2
0
        public IAsyncEnumerator <TResult> GetAsyncEnumerator(CancellationToken ct, AsyncIterationHint mode)
        {
            ct.ThrowIfCancellationRequested();
            IAsyncEnumerator <TSource>?inner = null;

            try
            {
                inner = this.Source is IConfigurableAsyncEnumerable <TSource> configurable?configurable.GetAsyncEnumerator(ct, mode) : this.Source.GetAsyncEnumerator(ct);

                Contract.Debug.Requires(inner != null, "The underlying async sequence returned an empty enumerator");

                var outer = this.Factory(inner);
                if (outer == null)
                {
                    throw new InvalidOperationException("The async factory returned en empty enumerator");
                }

                return(outer);
            }
            catch (Exception)
            {
                //make sure that the inner iterator gets disposed if something went wrong
                //BUGBUG: we have to block on the async disposable :(
                inner?.DisposeAsync().GetAwaiter().GetResult();
                throw;
            }
        }
 /// <summary>
 /// Ensure that both <paramref name="enumerator"/> and <paramref name="otherEnumerator"/> are disposed
 /// correctly and if an exception is thrown and <paramref name="outerException"/> is not null, throw an <see cref="AggregateException"/>
 /// that aggregate both the exception thrown by the enumerator/s and the exception containted in <paramref name="outerException"/>
 /// </summary>
 /// <param name="enumerator"></param>
 /// <param name="outerException"></param>
 /// <param name="otherEnumerator"></param>
 /// <returns></returns>
 /// <throw ><see cref="AggregateException"/></throw>
 public static async Task DisposeAsync(this IAsyncEnumerator enumerator, Exception outerException, IAsyncEnumerator otherEnumerator)
 {
     try
     {
         await Task.WhenAll(enumerator.DisposeAsync(), otherEnumerator.DisposeAsync());
     }
     catch (Exception ex)
     {
         if (outerException != null)
             throw new AggregateException(outerException, ex);
         throw;
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// Enumerates over all elements in the collection asynchronously
 /// </summary>
 /// <param name="enumerator">The collection of elements which can be enumerated asynchronously</param>
 /// <param name="action">A synchronous action to perform for every single item in the collection</param>
 /// <returns>Returns a Task which does enumeration over elements in the collection</returns>
 public static async Task ForEachAsync(this IAsyncEnumerator enumerator, Action <object> action)
 {
     try
     {
         while (await enumerator.MoveNextAsync().ConfigureAwait(false))
         {
             action(enumerator.Current);
         }
     }
     catch (ForEachAsyncBreakException)
     {
     }
     finally
     {
         await enumerator.DisposeAsync().ConfigureAwait(false);
     }
 }
Exemplo n.º 5
0
            public override async ValueTask DisposeAsync()
            {
                if (_enumerator != null)
                {
                    await _enumerator.DisposeAsync().ConfigureAwait(false);

                    _enumerator = null;
                }

                if (_resource != null)
                {
                    _resource.Dispose();
                    _resource = default;
                }

                await base.DisposeAsync().ConfigureAwait(false);
            }
Exemplo n.º 6
0
        private static async Task ForEachCore <T>(
            this IAsyncEnumerator <T> enumerator,
            Func <AsyncLoopContext <T>, Task> enumerationAction
            )
        {
            if (enumerationAction == null)
            {
                throw new ArgumentNullException("enumerationAction");
            }

            var index     = 0L;
            var loopState = new AsyncLoopContext <T>();

            ExceptionDispatchInfo edi = null;

            try
            {
                while (await enumerator.MoveNext().ConfigureAwait(false))
                {
                    loopState.Item  = enumerator.Current;
                    loopState.Index = index;
                    try
                    {
                        await enumerationAction(loopState).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        edi = ExceptionDispatchInfo.Capture(e);
                        break;
                    }

                    if (loopState.WasBreakCalled)
                    {
                        break;
                    }

                    index++;
                }
            }
            finally
            {
                await enumerator.DisposeAsync(edi?.SourceException);
            }

            edi?.Throw();
        }
        // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global
        public static async ValueTask AssertResult <T>(this IAsyncEnumerator <T> source, params T[] values)
        {
            var main    = default(Exception);
            var dispose = default(Exception);
            var idx     = 0;

            try
            {
                while (await source.MoveNextAsync())
                {
                    Assert.True(idx < values.Length, "Source has more than the expected " + values.Length + " items");
                    Assert.Equal(values[idx], source.Current);
                    idx++;
                }

                Assert.True(values.Length == idx, "Source has less items than expected: " + values.Length + ", actual: " + idx);
            }
            catch (Exception ex)
            {
                main = ex;
            }
            finally
            {
                try
                {
                    await source.DisposeAsync();
                }
                catch (Exception ex)
                {
                    dispose = ex;
                }
            }

            if (main != null && dispose != null)
            {
                throw new AggregateException(main, dispose);
            }
            if (main != null)
            {
                throw main;
            }
            if (dispose != null)
            {
                throw dispose;
            }
        }
Exemplo n.º 8
0
            public override async ValueTask DisposeAsync()
            {
                if (_resultEnumerator != null)
                {
                    await _resultEnumerator.DisposeAsync().ConfigureAwait(false);

                    _resultEnumerator = null;
                }

                if (_sourceEnumerator != null)
                {
                    await _sourceEnumerator.DisposeAsync().ConfigureAwait(false);

                    _sourceEnumerator = null;
                }

                await base.DisposeAsync().ConfigureAwait(false);
            }
        public async Task Dispose_CompletedEventIsRaised()
        {
            // arrange
            using var cts = new CancellationTokenSource(30000);
            var sent        = new EventMessage("foo", "bar");
            var eventStream = new InMemoryEventStream();
            IAsyncEnumerator <IEventMessage> enumerator = eventStream.GetAsyncEnumerator(cts.Token);
            bool eventRaised = false;

            eventStream.Completed += (s, e) => eventRaised = true;

            // act
            await enumerator.DisposeAsync();

            // assert
            Assert.True(eventRaised);
            Assert.False(await enumerator.MoveNextAsync());
        }
Exemplo n.º 10
0
            public override async ValueTask DisposeAsync()
            {
                if (_loserTask != null)
                {
                    await _loserTask.ConfigureAwait(false);

                    _loserTask  = null;
                    _enumerator = null;
                }
                else if (_enumerator != null)
                {
                    await _enumerator.DisposeAsync().ConfigureAwait(false);

                    _enumerator = null;
                }

                await base.DisposeAsync().ConfigureAwait(false);
            }
 protected override async ValueTask Cleanup()
 {
     try
     {
         if (m_chunkIterator != null)
         {
             await m_chunkIterator.DisposeAsync();
         }
     }
     finally
     {
         m_chunkIterator         = null;
         m_chunk                 = null;
         m_outOfChunks           = true;
         m_currentOffsetInChunk  = 0;
         m_itemsRemainingInChunk = 0;
     }
 }
Exemplo n.º 12
0
        public ODataResult <T> OData <T>(IAsyncEnumerable <T> asyncEnumerable)
        {
            IAsyncEnumerator <T> asyncEnumerator = asyncEnumerable.GetAsyncEnumerator();

            _httpContext.Response.OnCompleted(() => asyncEnumerator.DisposeAsync().AsTask());

            if (_odataUri != null && (OeExpressionHelper.IsPrimitiveType(typeof(T)) || _odataUri.Path.LastSegment is CountSegment))
            {
                return(new ODataPrimitiveResult <T>(_edmModel, _odataUri, asyncEnumerator));
            }

            if (_queryContext == null)
            {
                throw new InvalidOperationException("Must invoke OeAspQueryParser.ExecuteReader");
            }

            return(new ODataResult <T>(_queryContext, asyncEnumerator));
        }
        public async Task DeleteArchivedBlobsAsync(BlobServiceClient blobServiceClient, string blobContainerName, string blobNameFormat, int retainedBlobCountLimit)
        {
            if (retainedBlobCountLimit < 1)
            {
                throw new ArgumentException("Invalid value provided; retained blob count limit must be at least 1 or null.");
            }

            BlobContainerClient blobContainer = blobServiceClient.GetBlobContainerClient(blobContainerName);
            List <BlobItem>     logBlobs      = new List <BlobItem>();

            AsyncPageable <BlobItem> blobItems = blobContainer.GetBlobsAsync();

            IAsyncEnumerator <BlobItem> enumerator = blobItems.GetAsyncEnumerator();

            try
            {
                while (await enumerator.MoveNextAsync())
                {
                    logBlobs.Add(enumerator.Current);
                }
            }
            finally
            {
                await enumerator.DisposeAsync();
            }

            IEnumerable <BlobItem> validLogBlobs = logBlobs.Where(blobItem => DateTime.TryParseExact(
                                                                      RemoveRolledBlobNameSerialNum(blobItem.Name),
                                                                      blobNameFormat,
                                                                      CultureInfo.InvariantCulture,
                                                                      DateTimeStyles.AssumeLocal,
                                                                      out var _date));

            IEnumerable <BlobItem> blobsToDelete = validLogBlobs
                                                   .OrderByDescending(blobItem => blobItem.Name)
                                                   .Skip(retainedBlobCountLimit);

            foreach (var blobItem in blobsToDelete)
            {
                AppendBlobClient blobToDelete = blobContainer.GetAppendBlobClient(blobItem.Name);

                await blobToDelete.DeleteIfExistsAsync();
            }
        }
Exemplo n.º 14
0
        public async Task <List <string> > ListQueuesAsync()
        {
            var result    = new List <string>();
            var allQueues = queueServiceClient.GetQueuesAsync();
            IAsyncEnumerator <QueueItem> enumerator = allQueues.GetAsyncEnumerator();

            try
            {
                while (await enumerator.MoveNextAsync())
                {
                    result.Add(enumerator.Current.Name);
                }
            }
            finally
            {
                await enumerator.DisposeAsync();
            }
            return(result);
        }
        internal static IAsyncEnumerator <T> GetEnumerator(FdbAsyncSequenceQuery <T> sequence, AsyncIterationHint mode)
        {
            var generator = sequence.CompileSequence(sequence.Expression);

            if (sequence.Transaction != null)
            {
                var source = generator(sequence.Transaction);
                Contract.Assert(source != null);
                return(source is IConfigurableAsyncEnumerable <T> configurable?configurable.GetAsyncEnumerator(sequence.Transaction.Cancellation, mode) : source.GetAsyncEnumerator(sequence.Transaction.Cancellation));
            }

            //BUGBUG: how do we get a CancellationToken without a transaction?
            var ct = CancellationToken.None;

            IFdbTransaction?     trans    = null;
            IAsyncEnumerator <T>?iterator = null;
            bool success = true;

            try
            {
#warning Fix async begin transaction!
                trans = sequence.Database !.BeginTransactionAsync(ct).GetAwaiter().GetResult();                //HACKHACK: BUGBUG: async!
                var source = generator(trans);
                Contract.Assert(source != null);
                iterator = source is IConfigurableAsyncEnumerable <T> configurable?configurable.GetAsyncEnumerator(ct, mode) : source.GetAsyncEnumerator(ct);

                return(new TransactionIterator(trans, iterator));
            }
            catch (Exception)
            {
                success = false;
                throw;
            }
            finally
            {
                if (!success)
                {
                    //BUGBUG: we have to block on the async disposable :(
                    iterator?.DisposeAsync().GetAwaiter().GetResult();
                    trans?.Dispose();
                }
            }
        }
Exemplo n.º 16
0
        public void WillDisposeInternalEnumeratorAndEnumerableWhenDisposed()
        {
            MockRepository         mocks      = new MockRepository();
            IAsyncEnumerable <Row> enumerable = mocks.DynamicMultiMock <IAsyncEnumerable <Row> >(typeof(IAsyncDisposable));
            IAsyncEnumerator <Row> enumerator = mocks.DynamicMock <IAsyncEnumerator <Row> >();

            using (mocks.Record())
            {
                SetupResult.For(enumerable.GetAsyncEnumerator(Arg <CancellationToken> .Is.Anything)).Return(enumerator);
                SetupResult.For(enumerator.DisposeAsync()).Return(new ValueTask());
                SetupResult.For(((IAsyncDisposable)enumerable).DisposeAsync()).Return(new ValueTask());
            }
            using (mocks.Playback())
            {
                DictionaryEnumeratorDataReader reader =
                    new DictionaryEnumeratorDataReader(new Dictionary <string, Type>(), enumerable);
                reader.Dispose();
            }
        }
        public static IEnumerable <T> ToBlockingEnumerable <T>(this IAsyncEnumerable <T> source, CancellationToken cancellationToken = default)
        {
            IAsyncEnumerator <T> enumerator = source.GetAsyncEnumerator(cancellationToken);
            // A ManualResetEventSlim variant that lets us reuse the same
            // awaiter callback allocation across the entire enumeration.
            ManualResetEventWithAwaiterSupport?mres = null;

            try
            {
                while (true)
                {
#pragma warning disable CA2012 // Use ValueTasks correctly
                    ValueTask <bool> moveNextTask = enumerator.MoveNextAsync();
#pragma warning restore CA2012 // Use ValueTasks correctly

                    if (!moveNextTask.IsCompleted)
                    {
                        (mres ??= new()).Wait(moveNextTask.ConfigureAwait(false).GetAwaiter());
                        Debug.Assert(moveNextTask.IsCompleted);
                    }

                    if (!moveNextTask.Result)
                    {
                        yield break;
                    }

                    yield return(enumerator.Current);
                }
            }
            finally
            {
                ValueTask disposeTask = enumerator.DisposeAsync();

                if (!disposeTask.IsCompleted)
                {
                    (mres ?? new()).Wait(disposeTask.ConfigureAwait(false).GetAwaiter());
                    Debug.Assert(disposeTask.IsCompleted);
                }

                disposeTask.GetAwaiter().GetResult();
            }
        }
Exemplo n.º 18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproducts-async/{cost}")]
            HttpRequest req,
            [Sql("select * from Products where cost = @Cost",
                 CommandType = System.Data.CommandType.Text,
                 Parameters = "@Cost={cost}",
                 ConnectionStringSetting = "SqlConnectionString")]
            IAsyncEnumerable <Product> products)
        {
            IAsyncEnumerator <Product> enumerator = products.GetAsyncEnumerator();
            var productList = new List <Product>();

            while (await enumerator.MoveNextAsync())
            {
                productList.Add(enumerator.Current);
            }
            await enumerator.DisposeAsync();

            return((ActionResult) new OkObjectResult(productList));
        }
Exemplo n.º 19
0
        private static async Task Demo2Async()
        {
            var aDevice = new ADevice();

            IAsyncEnumerable <SensorData> en         = aDevice.GetSensorData1();
            IAsyncEnumerator <SensorData> enumerator = en.GetAsyncEnumerator();

            try
            {
                while (await enumerator.MoveNextAsync())
                {
                    var sensorData = enumerator.Current;
                    Console.WriteLine($"{sensorData.Value1} {sensorData.Value2}");
                }
            }
            finally
            {
                await enumerator.DisposeAsync();
            }
        }
Exemplo n.º 20
0
            static async IAsyncEnumerable <string> Demo2Async()
            {
                var aDevice = new Advice();

                IAsyncEnumerable <Event> en         = aDevice.GetSensorData1();
                IAsyncEnumerator <Event> enumerator = en.GetAsyncEnumerator();

                try
                {
                    while (await enumerator.MoveNextAsync())
                    {
                        var sendorData = enumerator.Current;
                        yield return($"Demo2 {sendorData.Score1} {sendorData.Score2}");
                    }
                }
                finally
                {
                    await enumerator.DisposeAsync();
                }
            }
Exemplo n.º 21
0
        public async static Task <IEnumerable <T> > AsyncToList <T>(IAsyncEnumerator <T> e)
        {
            IList <T> result = new List <T>();

            try
            {
                while (await e.MoveNextAsync())
                {
                    result.Add(e.Current);
                }
            }
            finally
            {
                if (e != null)
                {
                    await e.DisposeAsync();
                }
            }
            return(result);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Enumerates over all elements in the collection asynchronously
        /// </summary>
        /// <typeparam name="T">The type of elements in the collection</typeparam>
        /// <param name="enumerator">The collection of elements which can be enumerated asynchronously</param>
        /// <param name="action">A synchronous action to perform for every single item in the collection, where the second argument is the index of an item</param>
        /// <returns>Returns a Task which does enumeration over elements in the collection</returns>
        public static async Task ForEachAsync <T>(this IAsyncEnumerator <T> enumerator, Action <T, long> action)
        {
            try
            {
                long index = 0;

                while (await enumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    action(enumerator.Current, index);
                    index++;
                }
            }
            catch (ForEachAsyncBreakException)
            {
            }
            finally
            {
                await enumerator.DisposeAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 23
0
        public void ReceiveAllAsync_MultipleSingleElementEnumerations_AllItemsEnumerated(bool sameEnumerable, bool dispose)
        {
            var source = new BufferBlock <int>();
            IAsyncEnumerable <int> enumerable = source.ReceiveAllAsync();

            for (int i = 0; i < 10; i++)
            {
                Assert.True(source.Post(i));
                IAsyncEnumerator <int> e  = (sameEnumerable ? enumerable : source.ReceiveAllAsync()).GetAsyncEnumerator();
                ValueTask <bool>       vt = e.MoveNextAsync();
                Assert.True(vt.IsCompletedSuccessfully);
                Assert.True(vt.Result);
                Assert.Equal(i, e.Current);
                if (dispose)
                {
                    ValueTask dvt = e.DisposeAsync();
                    Assert.True(dvt.IsCompletedSuccessfully);
                    dvt.GetAwaiter().GetResult();
                }
            }
        }
        public void ReadAllAsync_MultipleSingleElementEnumerations_AllItemsEnumerated(bool sameEnumerable, bool dispose)
        {
            Channel <int>          c          = CreateChannel();
            IAsyncEnumerable <int> enumerable = c.Reader.ReadAllAsync();

            for (int i = 0; i < 10; i++)
            {
                Assert.True(c.Writer.TryWrite(i));
                IAsyncEnumerator <int> e  = (sameEnumerable ? enumerable : c.Reader.ReadAllAsync()).GetAsyncEnumerator();
                ValueTask <bool>       vt = e.MoveNextAsync();
                Assert.True(vt.IsCompletedSuccessfully);
                Assert.True(vt.Result);
                Assert.Equal(i, e.Current);
                if (dispose)
                {
                    ValueTask dvt = e.DisposeAsync();
                    Assert.True(dvt.IsCompletedSuccessfully);
                    dvt.GetAwaiter().GetResult();
                }
            }
        }
Exemplo n.º 25
0
        async Task TryPollOn(IAsyncEnumerator <int> en)
        {
            try
            {
                var f = en as IAsyncFusedEnumerator <int>;

                for (; ;)
                {
                    var v = f.TryPoll(out var state);
                    if (state != AsyncFusedState.Ready)
                    {
                        break;
                    }
                    Volatile.Write(ref field, v);
                }
            }
            finally
            {
                await en.DisposeAsync();
            }
        }
Exemplo n.º 26
0
        internal async Task <int> ConsumeStream()
        {
            IAsyncEnumerator <int> asyncEnumerator = GenerateSequence().GetAsyncEnumerator();

            try
            {
                while (await asyncEnumerator.MoveNextAsync())
                {
                    int number = asyncEnumerator.Current;
                    Console.WriteLine($"The time is {DateTime.Now:hh:mm:sssss}. Retrieved {number}");
                }
            }
            finally
            {
                if (asyncEnumerator != null)
                {
                    await asyncEnumerator.DisposeAsync();
                }
            }
            return(0);
        }
        /// <summary>List files</summary>
        /// <param name="directoryName">The directory of interest or null if you want the root directory</param>
        /// <param name="returnDirectoriesAndFiles">If true, you will get both directories and file.  If false, you will get only files.</param>
        /// <param name="cancellationToken"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <List <ShareFileItem> > ListFilesAsync(string directoryName,
                                                                 bool returnDirectoriesAndFiles, CancellationToken cancellationToken = default,
                                                                 ShareDirectoryGetFilesAndDirectoriesOptions options = null)
        {
            var result = new List <ShareFileItem>();

            ShareDirectoryClient directory = string.IsNullOrWhiteSpace(directoryName) ?
                                             _share.GetRootDirectoryClient() :
                                             _share.GetDirectoryClient(directoryName);


            // For >= C# 8.0 use:
            //await foreach (ShareFileItem fileItem in directory.GetFilesAndDirectoriesAsync(options, cancellationToken))
            //{
            //    result.Add(fileItem);
            //}

            // For < C# 8.0 use:
            AsyncPageable <ShareFileItem>    filePages  = directory.GetFilesAndDirectoriesAsync(options, cancellationToken);
            IAsyncEnumerator <ShareFileItem> enumerator = filePages.GetAsyncEnumerator();

            try
            {
                while (await enumerator.MoveNextAsync())
                {
                    if (returnDirectoriesAndFiles == false && enumerator.Current.IsDirectory)
                    {
                        continue;
                    }
                    result.Add(enumerator.Current);
                }
            }
            finally
            {
                await enumerator.DisposeAsync();
            }


            return(result);
        }
        public static async Task ForEachAsync <T>(this IAsyncEnumerable <T> source, Func <T, CancellationToken, Task> body, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }

            cancellationToken.ThrowIfCancellationRequested();

            IAsyncEnumerator <T> e = source.GetAsyncEnumerator();

            try
            {
                while (await e.WaitForNextAsync().ConfigureAwait(false))
                {
                    while (true)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        T item = e.TryGetNext(out bool success);

                        if (!success)
                        {
                            break;
                        }

                        await body(item, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
            finally
            {
                await e.DisposeAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 29
0
        public async Task <IActionResult> ProductSearch(string name)
        {
            if (name != string.Empty && name != null)
            {
                var productServiceClient = new ProductServiceClient();
                IAsyncEnumerator <ProductModel> products = productServiceClient.SearchProduct(name);

                var productList = new List <ProductModel>();

                while (await products.MoveNextAsync())
                {
                    productList.Add(products.Current);
                }
                await products.DisposeAsync();

                ViewData["ProductSearchName"] = name;

                return(View(productList));
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 30
0
            private async ValueTask DisposeAsync(bool dispose)
            {
                if (disposed)
                {
                    return;
                }

                try
                {
                    if (dispose)
                    {
                        if (null != enumerator)
                        {
                            await enumerator.DisposeAsync();
                        }
                    }
                }
                finally
                {
                    disposed = true;
                }
            }
Exemplo n.º 31
0
        public async ValueTask <(bool success, TItem item, TState state, bool last)> TryDequeue()
        {
            if (disposedValue)
            {
                throw new ObjectDisposedException(nameof(StreamQueue <TItem, TState>));
            }

            if (currentEnumerator != null)
            {
                return(await DequeueCached());
            }
            else if (queue.TryDequeue(out QueueItem queueItem))
            {
                if (queueItem.Items == null)
                {
                    return(true, queueItem.Item, queueItem.State, true);
                }
                else
                {
                    IAsyncEnumerator <TItem> enumerator = queueItem.Items.GetAsyncEnumerator();
                    bool next = await enumerator.MoveNextAsync().ConfigureAwait(false);

                    if (!next)
                    {
                        await enumerator.DisposeAsync().ConfigureAwait(false);

                        return(await TryDequeue().ConfigureAwait(false));
                    }
                    else
                    {
                        currentEnumerator = enumerator;
                        currentState      = queueItem.State;
                        return(await DequeueCached().ConfigureAwait(false));
                    }
                }
            }
            else
            {
                return(default);