Пример #1
0
        /// <summary>
        /// Starts a task that waits for the next rendering from Chrome.
        /// Chrome also renders the page loading, so if you want to see a complete rendering,
        /// only start this task once your page is loaded (which you can detect via FrameLoadEnd
        /// or your own heuristics based on evaluating JavaScript).
        /// It is your responsibility to dispose the returned Bitmap.
        /// The bitmap size is determined by the Size property set earlier.
        /// </summary>
        /// <param name="ignoreExistingScreenshot">Ignore existing bitmap (if any) and return the next avaliable bitmap</param>
        /// /// <param name="blend">Choose which bitmap to retrieve, choose <see cref="PopupBlending.Blend"/> for a merged bitmap.</param>
        /// <returns>Task&lt;Bitmap&gt;.</returns>
        public Task <Bitmap> ScreenshotAsync(bool ignoreExistingScreenshot = false, PopupBlending blend = PopupBlending.Main)
        {
            // Try our luck and see if there is already a screenshot, to save us creating a new thread for nothing.
            var screenshot = ScreenshotOrNull(blend);

            var completionSource = new AsyncTaskCompletionSource <Bitmap>();

            if (screenshot == null || ignoreExistingScreenshot)
            {
                EventHandler <OnPaintEventArgs> paint = null; // otherwise we cannot reference ourselves in the anonymous method below

                paint = (sender, e) =>
                {
                    // Chromium has rendered.  Tell the task about it.
                    Paint -= paint;

                    completionSource.TrySetResultAsync(ScreenshotOrNull());
                };

                Paint += paint;
            }
            else
            {
                completionSource.TrySetResultAsync(screenshot);
            }

            return(completionSource.Task);
        }
Пример #2
0
 protected override void Dispose(bool explicitDispose)
 {
     _nextSignalAwaitable = null;
     _signalState         = null;
     //
     base.Dispose(explicitDispose);
 }
        public Task WaitAsync(TimeSpan timeOut, CancellationToken token)
        {
            var tcs = new AsyncTaskCompletionSource();

            _tcs.Task.ContinueWith(t => tcs.TrySetResult());

            return(tcs.WaitWithTimeoutAndCancelAsync(timeOut, token));
        }
        public void WhenLauncherHasQueuedDelegate_ItShouldCompleted()
        {
            var sut = new SingleRunningDelegateLauncher();
            var tcs = new AsyncTaskCompletionSource();

            sut.Launch(ct => { tcs.SetResult(); }, t => { });

            ConcurrentAssert.EnsureThatTaskIsCompleted(tcs.Task);
        }
        public AsyncBarrier(int clientsCount)
        {
            if (clientsCount <= 0)
            {
                throw new ArgumentOutOfRangeException("clientsCount can not be less or equal to zero.");
            }

            _initialClientsCount = _clientsCount = clientsCount;
            _tcs = new AsyncTaskCompletionSource();
        }
Пример #6
0
 protected RunControlOperationState(RunControl <TComponent> runControl, TimeSpan beginTimestamp, CancellationToken ct)
 {
     runControl.EnsureNotNull(nameof(runControl));
     beginTimestamp.Arg(nameof(beginTimestamp)).EnsureNotLessThan(operand: TimeSpan.Zero);
     //
     RunControl       = runControl;
     BeginTimestamp   = beginTimestamp;
     Ct               = ct;
     _completionProxy = new AsyncTaskCompletionSource <IRunControlAttemptSuccess>(options: TaskCreationOptions.None);
     _completionProxy.Task.ContinueWith(continuationAction: P_LogAttemptContinuation, continuationOptions: TaskContinuationOptions.ExecuteSynchronously);
 }
        public void WhenLauncherHasQueuedDelegate_TheOnFinishedActionShouldBeCalledIf()
        {
            var  sut  = new SingleRunningDelegateLauncher();
            var  tcs  = new AsyncTaskCompletionSource();
            Task task = null;

            sut.Launch(ct => { }, t => { tcs.SetResult(); task = t; });

            ConcurrentAssert.EnsureThatTaskIsCompleted(tcs.Task);
            Assert.IsNotNull(task);
            Assert.IsTrue(task.IsCompleted);
            Assert.IsFalse(task.IsFaulted);
        }
Пример #8
0
        private AsyncTaskCompletionSource GetWaitingClientFromQueue()
        {
            AsyncTaskCompletionSource tcs = null;

            while (_waitingClientsQueue.TryDequeue(out tcs))
            {
                if (!tcs.Task.IsCompleted)
                {
                    return(tcs);
                }
            }

            return(null);
        }
Пример #9
0
        public Task WaitAsync()
        {
            lock (_lockObj)
            {
                if (_availableCount > 0)
                {
                    --_availableCount;
                    return(_completedTask);
                }

                var waiter = new AsyncTaskCompletionSource <Boolean>();
                _waiters.Enqueue(waiter);
                return(waiter.Task);
            }
        }
        public void WhenLauncherHasQueuedDelegate_TheOnFinishedActionShouldBeCalledAfterDelegateHasFinished()
        {
            var  sut  = new SingleRunningDelegateLauncher();
            var  tcs  = new AsyncTaskCompletionSource();
            var  tcs2 = new AsyncTaskCompletionSource();
            Task task = null;

            sut.Launch(ct => { tcs.Task.Wait(); }, t => { tcs2.SetResult(); task = t; });

            ConcurrentAssert.EnsureThatTaskIsNeverCompleted(tcs2.Task);

            tcs.SetResult();

            ConcurrentAssert.EnsureThatTaskIsCompleted(tcs2.Task);
        }
 public Task WaitAsync(TimeSpan timeout, CancellationToken token)
 {
     lock (_lock)
     {
         _clientsCount++;
         if (_clientsCount > _maxClientsCount)
         {
             var tcs = new AsyncTaskCompletionSource();
             _waitingClientsQueue.Enqueue(tcs);
             return(tcs.WaitWithTimeoutAndCancelAsync(timeout, token));
         }
         else
         {
             return(Task.CompletedTask);
         }
     }
 }
Пример #12
0
        public Task WaitAsync(CancellationToken cancellationToken)
        {
            lock (_lockObj)
            {
                if (_availableCount > 0)
                {
                    --_availableCount;
                    return(_completedTask);
                }

                var waiter = new AsyncTaskCompletionSource <Boolean>();
                _waiters.Enqueue(waiter);

                cancellationToken.Register(
                    OnCancelled, waiter);

                return(waiter.Task);
            }
        }
Пример #13
0
        public Task WaitAsync(TimeSpan timeOut, CancellationToken token)
        {
            AsyncTaskCompletionSource tcs = null;

            lock (_lock)
            {
                if (_isSignalState)
                {
                    _isSignalState = false;
                    return(Task.CompletedTask);
                }
                else
                {
                    tcs = new AsyncTaskCompletionSource();
                    _waitingClientsQueue.Enqueue(tcs);
                    return(tcs.WaitWithTimeoutAndCancelAsync(timeOut, token));
                }
            }
        }
Пример #14
0
        /// <summary>
        ///     Returns a task that will return the messages received on
        ///     <paramref
        ///         name="managedClient" />
        ///     when
        ///     <paramref
        ///         name="expectedNumberOfMessages" />
        ///     have been received
        /// </summary>
        Task <List <MqttApplicationMessage> > SetupReceivingOfMessages(ManagedMqttClient managedClient, int expectedNumberOfMessages)
        {
            var receivedMessages = new List <MqttApplicationMessage>();
            var result           = new AsyncTaskCompletionSource <List <MqttApplicationMessage> >();

            managedClient.ApplicationMessageReceivedAsync += e =>
            {
                receivedMessages.Add(e.ApplicationMessage);

                if (receivedMessages.Count == expectedNumberOfMessages)
                {
                    result.TrySetResult(receivedMessages);
                }

                return(PlatformAbstractionLayer.CompletedTask);
            };

            return(result.Task);
        }
Пример #15
0
 public Task <TriggerSignalEventArgs> NextSignalAwaitable()
 {
     try {
         var existingAwaitable = TryReadDA(ref _nextSignalAwaitable, considerDisposeRequest: true);
         if (existingAwaitable is null)
         {
             if (HasDeactivationRequested)
             {
                 return(TaskUtilities.FromCanceled <TriggerSignalEventArgs>());
             }
             else
             {
                 AsyncTaskCompletionSource <TriggerSignalEventArgs> newAwaitable = default;
                 try {
                     try {
                         UpdDAIfNullBool(location: ref _nextSignalAwaitable, factory: () => newAwaitable = new AsyncTaskCompletionSource <TriggerSignalEventArgs>(), current: out existingAwaitable);
                     }
                     catch (ObjectDisposedException) {
                         if (IsDisposeRequested)
                         {
                             return(TaskUtilities.FromCanceled <TriggerSignalEventArgs>());
                         }
                         else
                         {
                             throw;
                         }
                     }
                 }
                 finally {
                     if (!ReferenceEquals(existingAwaitable, newAwaitable))
                     {
                         newAwaitable?.TrySetCanceled(ct: CancellationToken.None);
                     }
                 }
             }
         }
         return(existingAwaitable.Task);
     }
     catch (Exception exception) {
         return(TaskUtilities.FromError <TriggerSignalEventArgs>(error: exception));
     }
 }
Пример #16
0
        public void Set()
        {
            AsyncTaskCompletionSource tcs = null;

            lock (_lock)
            {
                if (!_isSignalState)
                {
                    tcs = GetWaitingClientFromQueue();
                    if (tcs == null)
                    {
                        _isSignalState = true;
                    }
                    else
                    {
                        tcs.TrySetResult();
                    }
                }
            }
        }
        public Task <IDisposable> LockAsync(TimeSpan timeout, CancellationToken token)
        {
            var tcs = new AsyncTaskCompletionSource <IDisposable>();

            _am.EnterAsync(timeout, token).ContinueWith(t =>
            {
                if (t.IsCanceled)
                {
                    tcs.TrySetCanceled(token);
                }
                else if (t.IsFaulted)
                {
                    tcs.TrySetException(t.Exception);
                }
                else
                {
                    tcs.SetResult(new Disposable(_am));
                }
            });

            return(tcs.Task);
        }
        public Task SignalAndWaitAsync(TimeSpan timeout, CancellationToken token)
        {
            var tcs   = _tcs;
            var count = Interlocked.Decrement(ref _clientsCount);

            if (count < 0)
            {
                throw new InvalidOperationException("Can not signaled if counter is already less then zero.");
            }
            else if (count == 0)
            {
                _tcs          = new AsyncTaskCompletionSource();
                _clientsCount = _initialClientsCount;
                tcs.SetResult();
                return(tcs.Task);
            }
            else
            {
                var cancellableTcs = new AsyncTaskCompletionSource();
                tcs.Task.ContinueWith(t => cancellableTcs.TrySetResult());
                return(cancellableTcs.WaitWithTimeoutAndCancelAsync(timeout, token));
            }
        }
Пример #19
0
        /// <summary>
        /// Starts a task that waits for the next rendering from Chrome.
        /// Chrome also renders the page loading, so if you want to see a complete rendering,
        /// only start this task once your page is loaded (which you can detect via FrameLoadEnd
        /// or your own heuristics based on evaluating JavaScript).
        /// It is your responsibility to dispose the returned Bitmap.
        /// The bitmap size is determined by the Size property set earlier.
        /// </summary>
        /// <param name="ignoreExistingScreenshot">Ignore existing bitmap (if any) and return the next available bitmap</param>
        /// <param name="blend">Choose which bitmap to retrieve, choose <see cref="PopupBlending.Blend"/> for a merged bitmap.</param>
        /// <returns>Task&lt;Bitmap&gt;.</returns>
        public Task <Bitmap> ScreenshotAsync(bool ignoreExistingScreenshot = false, PopupBlending blend = PopupBlending.Main)
        {
            // Try our luck and see if there is already a screenshot, to save us creating a new thread for nothing.
            var screenshot = ScreenshotOrNull(blend);

            var completionSource = new AsyncTaskCompletionSource <Bitmap>();

            if (screenshot == null || ignoreExistingScreenshot)
            {
                EventHandler <OnPaintEventArgs> afterPaint = null; // otherwise we cannot reference ourselves in the anonymous method below

                afterPaint = (sender, e) =>
                {
                    // Chromium has rendered.  Tell the task about it.
                    AfterPaint -= afterPaint;

                    //If the user handled the Paint event then we'll throw an exception here
                    //as it's not possible to use ScreenShotAsync as the buffer wasn't updated.
                    if (e.Handled)
                    {
                        completionSource.TrySetException(new InvalidOperationException("OnPaintEventArgs.Handled = true, unable to process request. The buffer has not been updated"));
                    }
                    else
                    {
                        completionSource.TrySetResultAsync(ScreenshotOrNull(blend));
                    }
                };

                AfterPaint += afterPaint;
            }
            else
            {
                completionSource.TrySetResultAsync(screenshot);
            }

            return(completionSource.Task);
        }
Пример #20
0
        public Task <int> ReadAsync(byte[] buffer, int offset, int count, StreamMode mode)
        {
            System.Diagnostics.Debug.Assert(mConnectionOutputToEncoderInput == null);
            System.Diagnostics.Debug.Assert(buffer != null);
            System.Diagnostics.Debug.Assert(0 <= offset && offset < buffer.Length);
            System.Diagnostics.Debug.Assert(0 < count && count <= buffer.Length - offset);

            if (mEncoderOutputToConnectionInput != null)
            {
                return(mEncoderOutputToConnectionInput.ReadAsync(buffer, offset, count, mode));
            }

            lock (this)
            {
                // Multiple outstanding ReadAsync calls are not allowed.
                if (mBuffer != null)
                {
                    throw new InternalFailureException();
                }

                if (mComplete)
                {
                    return(Task.FromResult(0));
                }

                mBuffer = buffer;
                mOffset = offset;
                mEnding = offset + count;
                // CompletionSource must be async so we can complete it from within the lock.
                // If we move the completion outside the lock we may be able to do inline completion?
                mResult = AsyncTaskCompletionSource <int> .Create();

                Monitor.PulseAll(this);
                return(mResult.Task);
            }
        }
Пример #21
0
        public Task<int> ReadAsync(byte[] buffer, int offset, int count, StreamMode mode)
        {
            System.Diagnostics.Debug.Assert(mConnectionOutputToEncoderInput == null);
            System.Diagnostics.Debug.Assert(buffer != null);
            System.Diagnostics.Debug.Assert(0 <= offset && offset < buffer.Length);
            System.Diagnostics.Debug.Assert(0 < count && count <= buffer.Length - offset);

            if (mEncoderOutputToConnectionInput != null)
                return mEncoderOutputToConnectionInput.ReadAsync(buffer, offset, count, mode);

            lock (this)
            {
                // Multiple outstanding ReadAsync calls are not allowed.
                if (mBuffer != null)
                    throw new InternalFailureException();

                if (mComplete)
                    return Task.FromResult(0);

                mBuffer = buffer;
                mOffset = offset;
                mEnding = offset + count;
                // CompletionSource must be async so we can complete it from within the lock.
                // If we move the completion outside the lock we may be able to do inline completion?
                mResult = AsyncTaskCompletionSource<int>.Create();
                Monitor.PulseAll(this);
                return mResult.Task;
            }
        }
 public AsyncManualResetEvent()
 {
     _tcs = new AsyncTaskCompletionSource();
 }