public void TakeAsyncShouldBeThreadSafe()
        {
            const int expected   = 10;
            const int max        = 100;
            var       exit       = false;
            var       collection = new AsyncCollection <int>();

            var take1 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);
            var take2 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);
            var take3 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);

            take1.ContinueWith(t => Console.WriteLine("Take1 done..."));
            take2.ContinueWith(t => Console.WriteLine("Take2 done..."));
            take3.ContinueWith(t => Console.WriteLine("Take3 done..."));
            Task.WhenAll(take1, take2, take3).ContinueWith(x => exit = true);

            Parallel.ForEach(Enumerable.Range(0, max).ToList(),
                             new ParallelOptions {
                MaxDegreeOfParallelism = 20
            },
                             x =>
            {
                while (exit == false)
                {
                    collection.Add(x);
                    Thread.Sleep(100);
                }
            });

            Console.WriteLine("Left in collection: {0}", collection.Count);
            Assert.That(take1.Result.Count, Is.EqualTo(expected));
            Assert.That(take2.Result.Count, Is.EqualTo(expected));
            Assert.That(take3.Result.Count, Is.EqualTo(expected));
            Assert.That(collection.Count, Is.LessThan(max - (expected * 3)));
        }
        public void TakeAsyncFromMultipleThreads()
        {
            AsyncCollection <int> collection = new AsyncCollection <int>();
            int t1Counter = 0;
            int t2Counter = 0;

            var t1 = Task.Run(async() =>
            {
                while (!collection.IsCompleted)
                {
                    try
                    {
                        await collection.TakeAsync();
                        t1Counter++;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            });

            var t2 = Task.Run(async() =>
            {
                while (!collection.IsCompleted)
                {
                    try
                    {
                        await collection.TakeAsync();
                        t2Counter++;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            });

            for (int i = 0; i < 1000; i++)
            {
                collection.Add(i);
            }

            collection.CompleteAdding();

            t1.Wait();
            t2.Wait();

            Assert.IsTrue(t1Counter > 400);
            Assert.IsTrue(t2Counter > 400);
        }
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
        {
            int total = 0;

            while (count > 0 && !EndOfStream)
            {
                if (ReadBuffer != null && ReadOffset < ReadBuffer.Length)
                {
                    var read = Math.Min(ReadBuffer.Length - ReadOffset, count);
                    Array.Copy(ReadBuffer, ReadOffset, buffer, offset, read);
                    total      += read;
                    count      -= read;
                    offset     += read;
                    ReadOffset += read;
                }
                else
                {
                    ReadBuffer = await ReadQueue.TakeAsync(token);

                    ReadOffset = 0;
                    if (ReadBuffer == null)
                    {
                        EndOfStream = true;
                    }
                }
            }
            return(total);
        }
        public async void TakeAsyncShouldReturnEvenWhileMoreDataArrives()
        {
            var exit       = false;
            var collection = new AsyncCollection <int>();

            var sw       = Stopwatch.StartNew();
            var dataTask = collection.TakeAsync(10, TimeSpan.FromMilliseconds(5000), CancellationToken.None);


            var highVolumeAdding = Task.Factory.StartNew(() =>
            {
                //high volume of data adds
                while (exit == false)
                {
                    collection.Add(1);
                    Thread.Sleep(5);
                }
            });

            Console.WriteLine("Awaiting data...");
            await dataTask;

            Assert.That(dataTask.Result.Count, Is.EqualTo(10));
            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(5000));
            exit = true;

            Console.WriteLine("Waiting to unwind test...");
            await highVolumeAdding;
        }
        public async Task Process(CancellationToken cancellationToken)
        {
            while (true)
            {
                // The AsyncProducerConsumerQueue should never be in a completed state,
                // so DequeueAsync should only throw OperationCanceledException,
                // in which case the item should still be in the queue.
                var item = await input.TakeAsync(cancellationToken).ConfigureAwait(false);

                logger.ConditionalDebug("Processing \"{0}\"", item.Description);

                try
                {
                    await torrentClientStatus.WaitAsync().ConfigureAwait(false);
                    await AddItemAsync(item, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    // Put the item back in the queue, so it is not lost.
                    // Do not provide a CancellationToken to try to ensure that the operation succeeds.
                    logger.Warn("Adding \"{0}\" back into the queue due to failure", item.Description);
                    await input.AddAsync(item).ConfigureAwait(false);

                    if (ex is OperationCanceledException)
                    {
                        throw;
                    }
                    else
                    {
                        logger.Error(ex, "Adding torrent failed");
                    }
                }
            }
        }
        public async IAsyncEnumerable <Sample[]> EnumerateSamplesAsync(InputOption option, [EnumeratorCancellation] CancellationToken token = default)
        {
            if (string.IsNullOrEmpty(option.OptionName))
            {
                throw new ConfigurationNeededException();
            }

            var devices = GetDevices();
            var device  = devices.First(d => d.FriendlyName == option.OptionName);

            using var capture        = new WasapiLoopbackCapture(device);
            capture.ShareMode        = AudioClientShareMode.Shared;
            option.SamplingFrequency = capture.WaveFormat.SampleRate;
            bytesPerSample           = capture.WaveFormat.BitsPerSample / 8;

            EventHandler <WaveInEventArgs> handler = GetHandlerByEncoding(capture.WaveFormat.Encoding);

            capture.DataAvailable += handler;

            channels = capture.WaveFormat.Channels;
            //capture.WaveFormat = WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, 44100, 1, 44100 * 2, 2, 8 * 2);
            capture.StartRecording();

            while (await sampleQueue.OutputAvailableAsync(token))
            {
                var samples = await sampleQueue.TakeAsync(token);

                yield return(samples);
            }
            capture.DataAvailable -= handler;
        }
        /// <summary>
        /// This is used to avoid blocking low level hooks
        /// Otherwise if user takes long time to return the message
        /// OS will unsubscribe the hook
        /// Producer-consumer
        /// </summary>
        /// <returns></returns>
        private static async Task AppConsumer()
        {
            while (isRunning)
            {
                //blocking here until a key is added to the queue
                var item = await appQueue.TakeAsync();

                if (item is bool)
                {
                    break;
                }

                var wnd = (WindowData)item;
                switch (wnd.EventType)
                {
                case 0:
                    WindowCreated(wnd);
                    break;

                case 1:
                    WindowActivated(wnd);
                    break;

                case 2:
                    WindowDestroyed(wnd);
                    break;
                }
            }
        }
        public void TakeAsyncShouldPlayNiceWithTPL()
        {
            const int expected   = 200;
            const int max        = 400;
            var       exit       = false;
            var       collection = new AsyncCollection <int>();

            var dataTask = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);

            dataTask.ContinueWith(x => exit = true);

            Parallel.ForEach(Enumerable.Range(0, max).ToList(),
                             new ParallelOptions {
                MaxDegreeOfParallelism = 20
            },
                             x =>
            {
                while (exit == false)
                {
                    collection.Add(x);
                    Thread.Sleep(100);
                }
            });

            Console.WriteLine("Left in collection: {0}", collection.Count);
            Assert.That(dataTask.Result.Count, Is.EqualTo(expected));
            Assert.That(collection.Count, Is.LessThan(max - expected));
        }
        protected virtual async Task processQueuedItems()
        {
            while (!stopProcessingToken.IsCancellationRequested)
            {
                try
                {
                    var item = await taskQueue.TakeAsync(stopProcessingToken).ConfigureAwait(false);

                    if (item.CancelToken.HasValue && item.CancelToken.Value.IsCancellationRequested)
                    {
                        item.TaskSource.SetCanceled();
                    }
                    else
                    {
                        try
                        {
                            T result = await item.Action().ConfigureAwait(false);

                            item.TaskSource.SetResult(result);   // Indicate completion
                        }
                        catch (Exception ex)
                        {
                            if (ex is OperationCanceledException && ((OperationCanceledException)ex).CancellationToken == item.CancelToken)
                            {
                                item.TaskSource.SetCanceled();
                            }
                            item.TaskSource.SetException(ex);
                        }
                    }
                }
                catch (Exception) { }
            }
        }
Esempio n. 10
0
        private async Task UploadLoop()
        {
            while (await processingQueue.OutputAvailableAsync())
            {
                try {
                    var file = await processingQueue.TakeAsync();

                    file.UploadStatus = UploadStatus.InProgress;

                    // test if replay is eligible for upload (not AI, PTR, Custom, etc)
                    var replay = _analyzer.Analyze(file);
                    if (file.UploadStatus == UploadStatus.InProgress)
                    {
                        // if it is, upload it
                        await _uploader.Upload(replay, file);
                    }
                    SaveReplayList();
                    if (ShouldDelete(file, replay))
                    {
                        DeleteReplay(file);
                    }
                }
                catch (Exception ex) {
                    _log.Error(ex, "Error in upload loop");
                }
            }
        }
Esempio n. 11
0
    async Task Test()
    {
        var _asyncStack = new AsyncCollection <int>(
            new ConcurrentStack <int>(), maxCount: 1);



        // This Add completes immediately.
        await _asyncStack.AddAsync(7);

        // This Add (asynchronously) waits for the 7 to be removed
        // before it enqueues the 13.
        await _asyncStack.AddAsync(13);

        _asyncStack.CompleteAdding();



        while (true)
        {
            int item;
            try
            {
                item = await _asyncStack.TakeAsync();
            }
            catch (InvalidOperationException)
            {
                break;
            }
            Trace.WriteLine(item);
        }
    }
Esempio n. 12
0
        private async Task BatchSendAsync()
        {
            var outstandingSendTasks = new System.Collections.Concurrent.ConcurrentDictionary <Task, Task>();

            while (_asyncCollection.IsCompleted == false || _asyncCollection.Count > 0)
            {
                List <TopicMessage> batch = null;

                try
                {
                    try
                    {
                        batch = await _asyncCollection.TakeAsync(BatchSize, BatchDelayTime, _stopToken.Token).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException ex)
                    {
                        //TODO log that the operation was canceled, this only happens during a dispose
                    }

                    if (_asyncCollection.IsCompleted && _asyncCollection.Count > 0)
                    {
                        batch = batch ?? new List <TopicMessage>(_asyncCollection.Count);

                        //Drain any messages remaining in the queue and add them to the send batch
                        batch.AddRange(_asyncCollection.Drain());
                    }

                    //we want to fire the batch without blocking and then move on to fire another one
                    var sendTask = ProduceAndSendBatchAsync(batch, _stopToken.Token);

                    outstandingSendTasks.TryAdd(sendTask, sendTask);

                    var sendTaskCleanup = sendTask.ContinueWith(result =>
                    {
                        if (result.IsFaulted && batch != null)
                        {
                            batch.ForEach(x => x.Tcs.TrySetException(result.ExtractException()));
                        }

                        //TODO add statistics tracking
                        outstandingSendTasks.TryRemove(sendTask, out sendTask);
                    });
                }
                catch (Exception ex)
                {
                    if (batch != null)
                    {
                        batch.ForEach(x => x.Tcs.TrySetException(ex));
                    }
                }
            }

            var referenceToOutstanding = outstandingSendTasks.Values.ToList();

            if (referenceToOutstanding.Count > 0)
            {
                await Task.WhenAll(referenceToOutstanding).ConfigureAwait(false);
            }
        }
Esempio n. 13
0
        public async void TakeAsyncShouldReturnEmptyListIfNothingFound()
        {
            var aq = new AsyncCollection <bool>();

            var result = await aq.TakeAsync(100, TimeSpan.FromMilliseconds(100), CancellationToken.None).ConfigureAwait(false);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Count, Is.EqualTo(0));
        }
        /// <summary>
        /// Called by the <see cref="Code"/> implementation to check if the client wants to intercept a G/M/T-code
        /// </summary>
        /// <param name="code">Code to intercept</param>
        /// <returns>null if not intercepted or a <see cref="CodeResult"/> instance if resolved</returns>
        private async Task <CodeResult> Intercept(Code code)
        {
            // Avoid race conditions. A client can deal with only one code at once!
            using (await _lock.LockAsync(Program.CancelSource.Token))
            {
                // Send it to the interceptor
                await Connection.SendResponse(code);

                // Keep on processing commands from the interceptor until a handling result is returned.
                // This must be either an Ignore or a Resolve instruction!
                try
                {
                    while (await _commandQueue.OutputAvailableAsync(Program.CancelSource.Token))
                    {
                        BaseCommand command = await _commandQueue.TakeAsync(Program.CancelSource.Token);

                        // Code is ignored. Don't do anything with it but acknowledge the request
                        if (command is Ignore)
                        {
                            await Connection.SendResponse();

                            break;
                        }

                        // Code is resolved with a given result and the request is acknowledged
                        if (command is Resolve)
                        {
                            await Connection.SendResponse();

                            if ((command as Resolve).Content == null)
                            {
                                return(new CodeResult());
                            }
                            return(new CodeResult((command as Resolve).Type, (command as Resolve).Content));
                        }

                        // Deal with other requests
                        object result = command.Invoke();
                        await Connection.SendResponse(result);
                    }
                }
                catch (Exception e)
                {
                    if (Connection.IsConnected)
                    {
                        // Notify the client
                        await Connection.SendResponse(e);
                    }
                    else
                    {
                        Console.WriteLine("Intercept error: " + e.Message);
                    }
                }
            }
            return(null);
        }
Esempio n. 15
0
 public async Task <ArraySegment <byte> > TakeAsync(int size, CancellationToken cancellationToken = new CancellationToken())
 {
     if (cancellationToken.IsCancellationRequested)
     {
         throw new TaskCanceledException();
     }
     if (lastChunk == null)
     {
         lastChunk = await buffer.TakeAsync(cancellationToken);
     }
     return(ConsumeChunk(size));
 }
Esempio n. 16
0
        async void ReceiveAsync()
        {
            while (true)
            {
                while (await ReceiveQueue.OutputAvailableAsync().ConfigureAwait(false))
                {
                    var packet = await ReceiveQueue.TakeAsync().ConfigureAwait(false);

                    DataReceived?.Invoke(packet);
                }
            }
        }
Esempio n. 17
0
 public static async Task <bool> AsyncTest(int timeOut = 3000)
 {
     try {
         return(await AConnecting.TakeAsync(new CancellationTokenSource(timeOut).Token));
     } catch (Exception ex) {
         if (ex.InnerException is TaskCanceledException)
         {
             Console.WriteLine(ex.Message);
         }
         return(false);
     }
 }
Esempio n. 18
0
        public async void TakeAsyncShouldReturnAsSoonAsBatchSizeArrived()
        {
            var collection = new AsyncCollection <int>();

            var dataTask = collection.TakeAsync(10, TimeSpan.FromSeconds(5), CancellationToken.None);

            collection.AddRange(Enumerable.Range(0, 10));

            await dataTask;

            Assert.That(collection.Count, Is.EqualTo(0));
        }
        public async Task Process(CancellationToken cancellationToken)
        {
            while (await input.OutputAvailableAsync(cancellationToken).ConfigureAwait(false))
            {
                var item = await input.TakeAsync(cancellationToken).ConfigureAwait(false);

                logger.ConditionalDebug("Processing \"{0}\"", item.Title);

                // Do not pass a CancellationToken, so that the operation cannot be interrupted.
                var torrentItem = new Torrent(item.Url, true, item.Title);
                await output.AddAsync(torrentItem).ConfigureAwait(false);
            }
        }
        public async Task CancelTake()
        {
            AsyncCollection <int> collection = new AsyncCollection <int>();

            using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
            {
                var t = Task.Run(async() => await collection.TakeAsync(cancellationTokenSource.Token));

                cancellationTokenSource.Cancel();

                await Assert.ThrowsExceptionAsync <OperationCanceledException>(() => t);
            }
        }
Esempio n. 21
0
        public async void TakeAsyncShouldRemoveItemsFromCollection()
        {
            const int expectedCount = 10;

            var collection = new AsyncCollection <int>();

            collection.AddRange(Enumerable.Range(0, expectedCount));

            var data = await collection.TakeAsync(expectedCount, TimeSpan.FromMilliseconds(100), CancellationToken.None);

            Assert.That(data.Count, Is.EqualTo(expectedCount));
            Assert.That(collection.Count, Is.EqualTo(0));
        }
        public async Task AsyncTakeWithDelay()
        {
            AsyncCollection <int> collection = new AsyncCollection <int>();

            Task.Run(() =>
            {
                Thread.Sleep(100);
                collection.Add(1);
            });

            int item = await collection.TakeAsync();

            Assert.AreEqual(item, 1);
        }
Esempio n. 23
0
        public async void TakeAsyncShouldBePerformant()
        {
            const int             dataSize   = 1000000;
            AsyncCollection <int> collection = new AsyncCollection <int>();

            collection.AddRange(Enumerable.Range(0, dataSize));
            var sw   = Stopwatch.StartNew();
            var list = await collection.TakeAsync(dataSize, TimeSpan.FromSeconds(1), CancellationToken.None);

            sw.Stop();
            Console.WriteLine("Performance: {0}", sw.ElapsedMilliseconds);
            Assert.That(list.Count, Is.EqualTo(dataSize));
            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(200));
        }
Esempio n. 24
0
        /// <summary>
        /// Consume event from producer queue asynchronously
        /// </summary>
        /// <returns></returns>
        private static async Task ClipConsumerAsync()
        {
            while (isRunning)
            {
                var item = await clipQueue.TakeAsync();

                if (item is bool)
                {
                    break;
                }

                ClipboardHandler(item);
            }
        }
Esempio n. 25
0
        public async void CollectionShouldReportCorrectBufferCount()
        {
            var collection = new AsyncCollection<int>();

            var dataTask = collection.TakeAsync(10, TimeSpan.FromHours(5), CancellationToken.None);

            collection.AddRange(Enumerable.Range(0, 9));
            Assert.That(collection.Count, Is.EqualTo(9));

            collection.Add(1);
            var data = await dataTask;
            Assert.That(data.Count, Is.EqualTo(10));
            Assert.That(collection.Count, Is.EqualTo(0));
        }
Esempio n. 26
0
        public async void TakeAsyncShouldBeAbleToCancel()
        {
            var cancelSource = new CancellationTokenSource();
            var collection   = new AsyncCollection <int>();

            Task.Delay(TimeSpan.FromMilliseconds(100)).ContinueWith(t => cancelSource.Cancel());

            var sw   = Stopwatch.StartNew();
            var data = await collection.TakeAsync(10, TimeSpan.FromMilliseconds(500), cancelSource.Token);

            sw.Stop();

            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(300));
        }
Esempio n. 27
0
        public async void TakeAsyncShouldWaitXForBatchSizeToCollect()
        {
            const int expectedDelay = 100;
            const int expectedCount = 10;

            var collection = new AsyncCollection <int>();

            collection.AddRange(Enumerable.Range(0, expectedCount));

            var sw   = Stopwatch.StartNew();
            var data = await collection.TakeAsync(expectedCount + 1, TimeSpan.FromMilliseconds(expectedDelay), CancellationToken.None);

            Assert.That(sw.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(expectedDelay));
            Assert.That(data.Count, Is.EqualTo(expectedCount));
        }
Esempio n. 28
0
        /// <summary>
        /// Consume mouse events in our producer queue asynchronously
        /// </summary>
        /// <returns></returns>
        private static async Task ConsumeKeyAsync()
        {
            while (isRunning)
            {
                //blocking here until a key is added to the queue
                var item = await mouseQueue.TakeAsync();

                if (item is bool)
                {
                    break;
                }

                KListener_KeyDown(item as RawMouseEventArgs);
            }
        }
        // This is the method to run when the timer is raised.
        private static async Task ConsumeKeyAsync()
        {
            while (_IsRunning)
            {
                //blocking here until a key is added to the queue
                var item = await _kQueue.TakeAsync();

                if (item is bool)
                {
                    break;
                }

                KListener_KeyDown((KeyData)item);
            }
        }
Esempio n. 30
0
        public async void CollectionShouldReportCorrectBufferCount()
        {
            var collection = new AsyncCollection <int>();

            var dataTask = collection.TakeAsync(10, TimeSpan.FromHours(5), CancellationToken.None);

            collection.AddRange(Enumerable.Range(0, 9));
            Assert.That(collection.Count, Is.EqualTo(9));

            collection.Add(1);
            var data = await dataTask;

            Assert.That(data.Count, Is.EqualTo(10));
            Assert.That(collection.Count, Is.EqualTo(0));
        }
Esempio n. 31
0
        async Task EnableWriting()
        {
            try
            {
                while (await SendQueue.OutputAvailableAsync())
                {
                    var packet = await SendQueue.TakeAsync();

                    await Stream.WriteAsync(packet, 0, packet.Length);
                }
            }
            catch
            {
                RemoteDisconnect();
            }
        }
        public async Task AddAndRemoveShouldBePerformant()
        {
            AsyncCollection<int> collection = new AsyncCollection<int>();

            const int dataSize = 1000000;
            List<int> receivedData = null;// new List<int>(dataSize);
            var sw = Stopwatch.StartNew();

            var t = Task.Run(() => collection.AddRange(Enumerable.Range(0, dataSize)));
            var t2 = Task.Run(() => receivedData = collection.TakeAsync(dataSize, TimeSpan.FromSeconds(5), CancellationToken.None).Result);
            await Task.WhenAll(t, t2);
            sw.Stop();
            Console.WriteLine("Performance: {0}", sw.ElapsedMilliseconds);
            Assert.That(receivedData.Count, Is.EqualTo(dataSize));
            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(200));
        }
Esempio n. 33
0
        public async void TakeAsyncShouldRemoveItemsFromCollection()
        {
            const int expectedCount = 10;

            var collection = new AsyncCollection<int>();
            collection.AddRange(Enumerable.Range(0, expectedCount));

            var data = await collection.TakeAsync(expectedCount, TimeSpan.FromMilliseconds(100), CancellationToken.None);

            Assert.That(data.Count, Is.EqualTo(expectedCount));
            Assert.That(collection.Count, Is.EqualTo(0));
        }
Esempio n. 34
0
        public async void TakeAsyncShouldBeAbleToCancel()
        {
            var cancelSource = new CancellationTokenSource();
            var collection = new AsyncCollection<int>();

            Task.Delay(TimeSpan.FromMilliseconds(100)).ContinueWith(t => cancelSource.Cancel());

            var sw = Stopwatch.StartNew();
            var data = await collection.TakeAsync(10, TimeSpan.FromMilliseconds(500), cancelSource.Token);
            sw.Stop();

            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(300));
        }
        public async void TakeAsyncShouldOnlyWaitTimeoutAndReturnWhatItHas()
        {
            const int size = 20;
            var aq = new AsyncCollection<bool>();

            Task.Factory.StartNew(() =>
            {
                //this should take 2000ms to complete
                for (int i = 0; i < size; i++)
                {
                    aq.Add(true);
                    Thread.Sleep(100);
                }
            });

            var result = await aq.TakeAsync(size, TimeSpan.FromMilliseconds(100), CancellationToken.None);

            Assert.That(result.Count, Is.LessThan(size));
        }
        public async void TakeAsyncShouldReturnEmptyListIfNothingFound()
        {
            var aq = new AsyncCollection<bool>();

            var result = await aq.TakeAsync(100, TimeSpan.FromMilliseconds(100), CancellationToken.None).ConfigureAwait(false);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Count, Is.EqualTo(0));
        }
Esempio n. 37
0
        public void AddAndRemoveShouldBePerformant()
        {
            const int dataSize = 1000000;
            var collection = new AsyncCollection<int>();

            var sw = Stopwatch.StartNew();
            var receivedData = new List<int>();
            Parallel.Invoke(
                () => collection.AddRange(Enumerable.Range(0, dataSize)),
                () => receivedData = collection.TakeAsync(dataSize, TimeSpan.FromSeconds(5), CancellationToken.None).Result);
            sw.Stop();
            Console.WriteLine("Performance: {0}", sw.ElapsedMilliseconds);
            Assert.That(receivedData.Count, Is.EqualTo(dataSize));
            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(200));
        }
Esempio n. 38
0
        public async void TakeAsyncShouldWaitXForBatchSizeToCollect()
        {
            const int expectedDelay = 100;
            const int expectedCount = 10;

            var collection = new AsyncCollection<int>();
            collection.AddRange(Enumerable.Range(0, expectedCount));

            var sw = Stopwatch.StartNew();
            var data = await collection.TakeAsync(expectedCount + 1, TimeSpan.FromMilliseconds(expectedDelay), CancellationToken.None);

            Assert.That(sw.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(expectedDelay));
            Assert.That(data.Count, Is.EqualTo(expectedCount));
        }
Esempio n. 39
0
 public async void TakeAsyncShouldBePerformant()
 {
     const int dataSize = 1000000;
     var collection = new AsyncCollection<int>();
     collection.AddRange(Enumerable.Range(0, dataSize));
     var sw = Stopwatch.StartNew();
     var list = await collection.TakeAsync(dataSize, TimeSpan.FromSeconds(1), CancellationToken.None);
     sw.Stop();
     Console.WriteLine("Performance: {0}", sw.ElapsedMilliseconds);
     Assert.That(list.Count, Is.EqualTo(dataSize));
     Assert.That(sw.ElapsedMilliseconds, Is.LessThan(200));
 }
Esempio n. 40
0
        public void TakeAsyncShouldBeThreadSafe()
        {
            const int expected = 10;
            const int max = 100;
            var exit = false;
            var collection = new AsyncCollection<int>();

            var take1 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);
            var take2 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);
            var take3 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);

            take1.ContinueWith(t => Console.WriteLine("Take1 done..."));
            take2.ContinueWith(t => Console.WriteLine("Take2 done..."));
            take3.ContinueWith(t => Console.WriteLine("Take3 done..."));
            Task.WhenAll(take1, take2, take3).ContinueWith(x => exit = true);

            Parallel.ForEach(Enumerable.Range(0, max).ToList(),
                   new ParallelOptions { MaxDegreeOfParallelism = 20 },
                   x =>
                   {
                       while (exit == false)
                       {
                           collection.Add(x);
                           Thread.Sleep(100);
                       }
                   });

            Console.WriteLine("Left in collection: {0}", collection.Count);
            Assert.That(take1.Result.Count, Is.EqualTo(expected));
            Assert.That(take2.Result.Count, Is.EqualTo(expected));
            Assert.That(take3.Result.Count, Is.EqualTo(expected));
        }
Esempio n. 41
0
        public void TakeAsyncShouldPlayNiceWithTPL()
        {
            const int expected = 200;
            const int max = 400;
            var exit = false;
            var collection = new AsyncCollection<int>();

            var dataTask = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None);

            dataTask.ContinueWith(x => exit = true);

            Parallel.ForEach(Enumerable.Range(0, max).ToList(),
                   new ParallelOptions { MaxDegreeOfParallelism = 20 },
                   x =>
                   {
                       while (exit == false)
                       {
                           collection.Add(x);
                           Thread.Sleep(100);
                       }
                   });

            Console.WriteLine("Left in collection: {0}", collection.Count);
            Assert.That(dataTask.Result.Count, Is.EqualTo(expected));
        }
Esempio n. 42
0
        public async void TakeAsyncShouldReturnEvenWhileMoreDataArrives()
        {
            var exit = false;
            var collection = new AsyncCollection<int>();

            var sw = Stopwatch.StartNew();
            var dataTask = collection.TakeAsync(10, TimeSpan.FromMilliseconds(5000), CancellationToken.None);


            var highVolumeAdding = Task.Run(() =>
            {
                //high volume of data adds
                while (exit == false)
                {
                    collection.Add(1);
                    Thread.Sleep(5);
                }
            });

            Console.WriteLine("Awaiting data...");
            await dataTask;

            Assert.That(dataTask.Result.Count, Is.EqualTo(10));
            Assert.That(sw.ElapsedMilliseconds, Is.LessThan(5000));
            exit = true;

            Console.WriteLine("Waiting to unwind test...");
            await highVolumeAdding;
        }
Esempio n. 43
0
        public async void TakeAsyncShouldReturnAsSoonAsBatchSizeArrived()
        {
            var collection = new AsyncCollection<int>();

            var dataTask = collection.TakeAsync(10, TimeSpan.FromSeconds(5), CancellationToken.None);

            collection.AddRange(Enumerable.Range(0, 10));

            await dataTask;

            Assert.That(collection.Count, Is.EqualTo(0));

        }