Esempio n. 1
0
        public void OnDataAvailableShouldTriggerWhenDataAdded()
        {
            var aq = new AsyncCollection <bool>();

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");

            aq.Add(true);

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available.");
        }
Esempio n. 2
0
        public void OnDataAvailableShouldTriggerWhenDataAdded()
        {
            var aq = new AsyncCollection<bool>();

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");

            aq.Add(true);

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available.");
        }
Esempio n. 3
0
        public void TryTakeShouldReturnFalseOnEmpty()
        {
            var aq = new AsyncCollection <bool>();

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");

            bool data;

            Assert.That(aq.TryTake(out data), Is.False, "TryTake should report false on empty collection.");
            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");
        }
Esempio n. 4
0
        public void DrainShouldBlockWhenDataRemoved()
        {
            var aq = new AsyncCollection<bool>();

            aq.Add(true);
            aq.Add(true);

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available.");

            var drained = aq.Drain().ToList();
            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");
        }
Esempio n. 5
0
        public void OnDataAvailableShouldBlockWhenDataRemoved()
        {
            var aq = new AsyncCollection<bool>();

            aq.Add(true);

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available.");

            bool data;
            aq.TryTake(out data);
            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");
        }
Esempio n. 6
0
        public void DrainShouldBlockWhenDataRemoved()
        {
            var aq = new AsyncCollection <bool>();

            aq.Add(true);
            aq.Add(true);

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available.");

            var drained = aq.Drain().ToList();

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");
        }
Esempio n. 7
0
        public void OnDataAvailableShouldBlockWhenDataRemoved()
        {
            var aq = new AsyncCollection <bool>();

            aq.Add(true);

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available.");

            bool data;

            aq.TryTake(out data);
            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");
        }
Esempio n. 8
0
        public async void OnDataAvailableShouldCancel()
        {
            var aq = new AsyncCollection<bool>();
            var cancelToken = new CancellationTokenSource();
            Task.Delay(TimeSpan.FromMilliseconds(100)).ContinueWith(t => cancelToken.Cancel());

            await aq.OnHasDataAvailable(cancelToken.Token);
        }
        public async void OnDataAvailableShouldCancel()
        {
            var aq          = new AsyncCollection <bool>();
            var cancelToken = new CancellationTokenSource();

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

            await aq.OnHasDataAvailable(cancelToken.Token);
        }
 public async Task OnDataAvailableShouldCancel()//change class Behavers from trowing OperationCanceledException to returning false
 {//do not debug with brack point it harm this test
     var aq = new AsyncCollection<bool>();
     int timeSpen = 100;
     Task waitUntilCancel = aq.OnHasDataAvailable(new CancellationTokenSource(timeSpen).Token);
     await Task.WhenAny(waitUntilCancel, Task.Delay(timeSpen / 2));
     Assert.IsFalse(waitUntilCancel.IsCompleted, "task Should Cancel only when time is up");
     //ToDO FIX
     //   Assert.IsFalse(await waitUntilCancel, "it Should return false when cancel");
 }
Esempio n. 11
0
        public async Task OnDataAvailableShouldCancel() //change class Behavers from trowing OperationCanceledException to returning false
        {                                               //do not debug with brack point it harm this test
            var  aq              = new AsyncCollection <bool>();
            int  timeSpen        = 100;
            Task waitUntilCancel = aq.OnHasDataAvailable(new CancellationTokenSource(timeSpen).Token);
            await Task.WhenAny(waitUntilCancel, Task.Delay(timeSpen / 2));

            Assert.IsFalse(waitUntilCancel.IsCompleted, "task Should Cancel only when time is up");
            //ToDO FIX
            //   Assert.IsFalse(await waitUntilCancel, "it Should return false when cancel");
        }
Esempio n. 12
0
        private async Task BatchSendAsync()
        {
            while (IsNotDisposedOrHasMessagesToProcess())
            {
                List <TopicMessage> batch = null;

                try
                {
                    try
                    {
                        await _asyncCollection.OnHasDataAvailable(_stopToken.Token).ConfigureAwait(false);

                        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());
                    }
                    if (batch != null)
                    {
                        await ProduceAndSendBatchAsync(batch, _stopToken.Token).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    if (batch != null)
                    {
                        batch.ForEach(x => x.Tcs.TrySetException(ex));
                    }
                }
            }
        }
Esempio n. 13
0
        private void ProcessNetworkstreamTasks(Stream netStream)
        {
            Task writeTask = Task.FromResult(true);
            Task readTask  = Task.FromResult(true);

            //reading/writing from network steam is not thread safe
            //Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization.
            //As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference
            //between read and write threads and no synchronization is required.
            //https://msdn.microsoft.com/en-us/library/z2xae4f4.aspx
            while (_disposeToken.IsCancellationRequested == false && netStream != null)
            {
                Task sendDataReady = Task.WhenAll(writeTask, _sendTaskQueue.OnHasDataAvailable(_disposeToken.Token));
                Task readDataReady = Task.WhenAll(readTask, _readTaskQueue.OnHasDataAvailable(_disposeToken.Token));

                Task.WaitAny(sendDataReady, readDataReady);

                var exception = new[] { writeTask, readTask }
                .Where(x => x.IsFaulted && x.Exception != null)
                .SelectMany(x => x.Exception.InnerExceptions)
                .FirstOrDefault();

                if (exception != null)
                {
                    throw exception;
                }

                if (sendDataReady.IsCompleted)
                {
                    writeTask = ProcessSentTasksAsync(netStream, _sendTaskQueue.Pop());
                }
                if (readDataReady.IsCompleted)
                {
                    readTask = ProcessReadTaskAsync(netStream, _readTaskQueue.Pop());
                }
            }
        }
Esempio n. 14
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
                    {
                        await _asyncCollection.OnHasDataAvailable(_stopToken.Token).ConfigureAwait(false);

                        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. 15
0
        public void TryTakeShouldReturnFalseOnEmpty()
        {
            var aq = new AsyncCollection<bool>();

            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");

            bool data;
            Assert.That(aq.TryTake(out data), Is.False, "TryTake should report false on empty collection.");
            Assert.That(aq.OnHasDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available.");
        }