internal static void SetReplicableNull(Task? task)
 {
     try
     {
         replicableLock.Enter();
         if (!task.HasValue || (replicable.HasValue && replicable.Value.ID == task.Value.ID && replicable.Value.Item == task.Value.Item))
             replicable = null;
     }
     finally
     {
         replicableLock.Exit();
     }
 }
Exemple #2
0
        internal async Task <IObjectPrx?> InvokeAsync(Func <ILookupPrx, ILookupReplyPrx, Task> find, LookupReply replyServant)
        {
            Identity requestId = _replyAdapter.AddWithUUID(replyServant, ILocatorRegistryPrx.Factory).Identity;

            Task <IObjectPrx?> replyTask = replyServant.CompletionSource.Task;

            try
            {
                for (int i = 0; i < _retryCount; ++i)
                {
                    long start        = DateTime.Now.Ticks;
                    int  failureCount = 0;
                    foreach ((ILookupPrx lookup, ILookupReplyPrx? reply) in _lookups)
                    {
                        ILookupReplyPrx?lookupReply = reply.Clone(requestId, ILookupReplyPrx.Factory);
                        try
                        {
                            await find(lookup, lookupReply);
                        }
                        catch (Exception ex)
                        {
                            if (++failureCount == _lookups.Count)
                            {
                                _lookup.Communicator.Logger.Warning(ex.ToString());
                                replyServant.CompletionSource.SetResult(null);
                            }
                        }
                    }

                    Task?t = await Task.WhenAny(replyTask,
                                                Task.Delay(_timeout, replyServant.CancellationSource.Token)).ConfigureAwait(false);

                    if (t == replyTask)
                    {
                        return(await replyTask.ConfigureAwait(false)); // We're done!
                    }
                    else if (t.IsCanceled)
                    {
                        // If the timeout was canceled we delay the completion of the request to give a chance to other
                        // members of this replica group to reply
                        return(await replyServant.WaitForReplicaGroupRepliesAsync(start, _latencyMultiplier));
                    }
                }
                replyServant.CompletionSource.SetResult(null); // Timeout
                return(await replyTask.ConfigureAwait(false));
            }
            finally
            {
                _replyAdapter.Remove(requestId);
            }
        }
Exemple #3
0
        /// <summary>Spawns an asynchronous polling loop for process completion.</summary>
        /// <param name="cancellationToken">A token to monitor to exit the polling loop.</param>
        /// <returns>The task representing the loop.</returns>
        private Task WaitForExitAsync(CancellationToken cancellationToken = default)
        {
            Debug.Assert(Monitor.IsEntered(_gate));
            Debug.Assert(_waitInProgress == null);
            Debug.Assert(!_isChild);

            return(_waitInProgress = Task.Run(async delegate // Task.Run used because of potential blocking in CheckForNonChildExit
            {
                // Arbitrary values chosen to balance delays with polling overhead.  Start with fast polling
                // to handle quickly completing processes, but fall back to longer polling to minimize
                // overhead for those that take longer to complete.
                const int StartingPollingIntervalMs = 1, MaxPollingIntervalMs = 100;
                int pollingIntervalMs = StartingPollingIntervalMs;

                try
                {
                    // While we're not canceled
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        // Poll
                        lock (_gate)
                        {
                            if (!_exited)
                            {
                                CheckForNonChildExit();
                            }
                            if (_exited) // may have been updated by CheckForNonChildExit
                            {
                                return;
                            }
                        }

                        // Wait
                        try
                        {
                            await Task.Delay(pollingIntervalMs, cancellationToken).ConfigureAwait(false);
                            pollingIntervalMs = Math.Min(pollingIntervalMs * 2, MaxPollingIntervalMs);
                        }
                        catch (OperationCanceledException) { }
                    }
                }
                finally
                {
                    // Task is no longer active
                    lock (_gate)
                    {
                        _waitInProgress = null;
                    }
                }
            }, cancellationToken));
        }
Exemple #4
0
        public async Task ExecuteMassiveDelete()
        {
            var dbId = TestConfig.GetDedicatedDB();
            var key  = Me();

            Prep(dbId, key);
            var watch = Stopwatch.StartNew();

            using (var muxer = Create())
                using (var throttle = new SemaphoreSlim(1))
                {
                    var conn       = muxer.GetDatabase(dbId);
                    var originally = await conn.SetLengthAsync(key).ForAwait();

                    int  keepChecking = 1;
                    Task?last         = null;
                    while (Volatile.Read(ref keepChecking) == 1)
                    {
                        throttle.Wait(); // acquire
                        var x = conn.SetPopAsync(key).ContinueWith(task =>
                        {
                            throttle.Release();
                            if (task.IsCompleted)
                            {
                                if ((string)task.Result == null)
                                {
                                    Volatile.Write(ref keepChecking, 0);
                                }
                                else
                                {
                                    last = conn.KeyDeleteAsync((string)task.Result);
                                }
                            }
                        });
                        GC.KeepAlive(x);
                    }
                    if (last != null)
                    {
                        await last;
                    }
                    watch.Stop();
                    long remaining = await conn.SetLengthAsync(key).ForAwait();

                    Log("From {0} to {1}; {2}ms", originally, remaining,
                        watch.ElapsedMilliseconds);

                    var counters = GetServer(muxer).GetCounters();
                    Log("Completions: {0} sync, {1} async", counters.Interactive.CompletedSynchronously, counters.Interactive.CompletedAsynchronously);
                }
        }
        public void Start(CancellationToken stoppingToken)
        {
            stoppingToken.Register(() => _cts.Cancel());

            _logger.ServerStarting();

            _context = new ProcessingContext(_provider, _cts.Token);

            var processorTasks = GetProcessors()
                                 .Select(InfiniteRetry)
                                 .Select(p => p.ProcessAsync(_context));

            _compositeTask = Task.WhenAll(processorTasks);
        }
        internal FollowerState StartServing(TimeSpan timeout, CancellationToken token)
        {
            if (token.IsCancellationRequested)
            {
                trackerCancellation.Cancel(false);
                tracker = null;
            }
            else
            {
                tracker = Track(timeout, refreshEvent, stateMachine.MoveToCandidateState, trackerCancellation.Token, token);
            }

            return(this);
        }
        public void Run()
        {
            if (mainTask != null)
            {
                throw new InvalidOperationException("Game is already running");
            }

            if (fatalException != null)
            {
                throw new InvalidOperationException("Game already failed", fatalException);
            }

            mainTask = Task.Run(MainAsync);
        }
Exemple #8
0
        /// <summary>
        /// Resumes rendering when in suspend state.
        /// </summary>
        public void Resume()
        {
            if (_suspendWaiter != null)
            {
                if (!_suspendCallWaiterSource !.Task.IsCompleted)
                {
                    _suspendCallWaiterSource.TrySetResult(null);
                }

                _suspendWaiterSource !.TrySetResult(null);
                _suspendWaiterSource = null;
                _suspendWaiter       = null;
            }
        }
Exemple #9
0
        /// <summary>Логика выполнения - Выполнить операцию</summary>
        private Task OnStartCommandExecutedAsync(object?p)
        {
            Error         = null;
            _Cancellation = new CancellationTokenSource();
            var cancel = _Cancellation.Token;

            _Timer         = Stopwatch.StartNew();
            _OperationTask = _Execute(p, new Progress <double>(progress => Progress = progress), cancel);
            InProgress     = true;

            _ = _OperationTask.ContinueWith(OnOperationCompletedAsync, CancellationToken.None);

            return(_OperationTask);
        }
Exemple #10
0
    public static async Task WithTimeout(this Task?task, TimeSpan timeout)
    {
        task    = GuardTask(task);
        timeout = GuardTimeout(timeout);

        using var cts = new CancellationTokenSource();
        if (task != await Task.WhenAny(task, Task.Delay(timeout, cts.Token)).ForAwait())
        {
            ThrowTimeoutException(timeout);
        }

        cts.Cancel();
        await task.ForAwait();
    }
        public void Start()
        {
            if (Status != WorkerStatus.Stopped)
            {
                throw new InvalidOperationException("Worker must be stopped in order to start it");
            }

            Status = WorkerStatus.Starting;

            _cancellationTokenSource = new CancellationTokenSource();
            _worker = _workerWrapper(_cancellationTokenSource.Token);

            OnStarted?.Invoke(this, new EventArgs());
        }
        /// <summary>
        /// Starts voting asynchronously.
        /// </summary>
        /// <param name="timeout">Candidate state timeout.</param>
        /// <param name="auditTrail">The local transaction log.</param>
        internal CandidateState StartVoting(int timeout, IAuditTrail <IRaftLogEntry> auditTrail)
        {
            stateMachine.Logger.VotingStarted(timeout);
            ICollection <VotingState> voters = new LinkedList <VotingState>();

            votingCancellation.CancelAfter(timeout);
            //start voting in parallel
            foreach (var member in stateMachine.Members)
            {
                voters.Add(new VotingState(member, Term, auditTrail, votingCancellation.Token));
            }
            votingTask = EndVoting(voters);
            return(this);
        }
Exemple #13
0
        private async Task ConnectAsync(CancellationToken cancellationToken)
        {
            _connection = await _connectionFactory.ConnectAsync(_endpoint, null, cancellationToken)
                          .ConfigureAwait(false);

            if (_connection is null)
            {
                ThrowHelper.ConnectionException <bool>(_endpoint);
            }

            _reader      = new ProtocolReader(_connection.Pipe.Input);
            _writer      = new ProtocolWriter(_connection.Pipe.Output);
            _readingTask = StartReadAsync();
        }
Exemple #14
0
        // User calls BeginRead to start the asynchronous read
        internal void BeginReadLine()
        {
            _cancelOperation = false;

            if (_sb == null)
            {
                _sb = new StringBuilder(DefaultBufferSize);
                _readToBufferTask = Task.Run((Func <Task>)ReadBufferAsync);
            }
            else
            {
                FlushMessageQueue(rethrowInNewThread: false);
            }
        }
Exemple #15
0
        /// <summary>Gets a Task to represent the asynchronous operation.</summary>
        /// <param name="source">The asynchronous operation.</param>
        /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
        /// <returns>The Task representing the asynchronous operation.</returns>
        public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
            var wrapper = source as TaskToAsyncActionAdapter;

            if (wrapper != null && !wrapper.CompletedSynchronously)
            {
                Task?innerTask = wrapper.Task;
                Debug.Assert(innerTask != null);
                Debug.Assert(innerTask.Status != TaskStatus.Created);

                if (!innerTask.IsCompleted)
                {
                    // The race here is benign: If the task completes here, the concatination is useless, but not damaging.
                    if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
                    {
                        ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
                    }
                }

                return(innerTask);
            }

            // Fast path to return a completed Task if the operation has already completed:
            switch (source.Status)
            {
            case AsyncStatus.Completed:
                return(Task.CompletedTask);

            case AsyncStatus.Error:
                return(Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)));

            case AsyncStatus.Canceled:
                return(Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)));
            }

            // Benign race: source may complete here. Things still work, just not taking the fast path.

            // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
            var bridge = new AsyncInfoToTaskBridge <VoidValueTypeParameter, VoidValueTypeParameter>(cancellationToken);

            source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction);
            bridge.RegisterForCancellation(source);
            return(bridge.Task);
        }
Exemple #16
0
 private void MaybeCreateTimeoutTask()
 {
     // If there are no active clients running then the server needs to be in a timeout mode.
     if (
         _state == State.Running &&
         _connectionList.Count == 0 &&
         _timeoutTask is null &&
         _keepAlive.HasValue
         )
     {
         Debug.Assert(_listenTask != null);
         _timeoutTask = Task.Delay(_keepAlive.Value);
     }
 }
Exemple #17
0
        public async Task StartAsync(CancellationToken ct)
        {
            ct.ThrowIfCancellationRequested();

            await OnStart(ct);

            _workerCancellationTokenSource = new CancellationTokenSource();
            _workerTask = Task.Factory.StartNew(
                async() => await InternalLoop(_workerCancellationTokenSource.Token),
                _workerCancellationTokenSource.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default)
                          .Unwrap();
        }
Exemple #18
0
 public Task <IDisposable> Subscribe(IObserver <int> observer)
 {
     this.Observer          = observer;
     this.FireAndForgetTask = Task.Run(delegate
     {
         observer.OnNext(1);
         observer.OnNext(2);
     });
     return(Task.FromResult <IDisposable>(new DisposableAction(() =>
     {
         ((IDisposable)observer).Dispose();
         this.SubscriptionIsDisposed.Set();
     })));
 }
Exemple #19
0
        /// <summary>
        /// This function will accept and process new connections until an event causes
        /// the server to enter a passive shut down mode.  For example if analyzers change
        /// or the keep alive timeout is hit.  At which point this function will cease
        /// accepting new connections and wait for existing connections to complete before
        /// returning.
        /// </summary>
        public void ListenAndDispatchConnections(TimeSpan?keepAlive, CancellationToken cancellationToken = default)
        {
            _state              = State.Running;
            _keepAlive          = keepAlive;
            _keepAliveIsDefault = true;

            try
            {
                _clientConnectionHost.BeginListening();
                ListenAndDispatchConnectionsCore(cancellationToken);
            }
            finally
            {
                _state       = State.Completed;
                _gcTask      = null;
                _timeoutTask = null;

                if (_clientConnectionHost.IsListening)
                {
                    _clientConnectionHost.EndListening();
                }

                if (_listenTask is not null)
                {
                    // This type is responsible for cleaning up resources associated with _listenTask. Once EndListening
                    // is complete this task is guaranteed to be either completed or have a task scheduled to complete
                    // it. If it ran to completion we need to dispose of the value.
                    if (!_listenTask.IsCompleted)
                    {
                        // Wait for the task to complete
                        _listenTask.ContinueWith(_ => { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)
                        .Wait(CancellationToken.None);
                    }

                    if (_listenTask.Status == TaskStatus.RanToCompletion)
                    {
                        try
                        {
                            _listenTask.Result.Dispose();
                        }
                        catch (Exception ex)
                        {
                            CompilerServerLogger.LogException(ex, $"Error disposing of {nameof(_listenTask)}");
                        }
                    }
                }
            }
            CompilerServerLogger.Log($"End ListenAndDispatchConnections");
        }
Exemple #20
0
        public Task <Maybe <TOutput> > ReceiveAsync(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                ct.ThrowIfCancellationRequested();
            }

            // if the first item in the queue is completed, we return it immediately (fast path)
            // if the first item in the queue is not yet completed, we need to wait for it (semi-fast path)
            // if the queue is empty, we first need to wait for an item to arrive, then wait for it

            Task <Maybe <TOutput> >?task = null;
            Task?waiter = null;

            lock (m_lock)
            {
                if (m_queue.Count > 0)
                {
                    task = m_queue.Peek();
                    Contract.Debug.Assert(task != null);

                    if (task.IsCompleted)
                    {
                        m_queue.Dequeue();
                        WakeUpProducer_NeedsLocking();
                        return(Maybe.Unwrap(task));
                    }
                }
                else if (m_done)
                {                 // something went wrong...
                    return(Maybe <TOutput> .EmptyTask);
                }
                else
                {
                    waiter = WaitForNextItem_NeedsLocking(ct);
                    Contract.Debug.Assert(waiter != null);
                }
            }

            if (task != null)
            {             // the next task is already started, we need to wait for it
                return(ReceiveWhenDoneAsync(task, ct));
            }
            else
            {             // nothing scheduled yet, slow code path will wait for something new to happen...
                Contract.Debug.Assert(waiter != null);
                return(ReceiveSlowAsync(waiter, ct));
            }
        }
Exemple #21
0
        public StreamDevice(
            IDeviceAdapter adapter,
            IDeviceDefinition device,
            CancellationToken token     = default,
            int minimumTrasmissionDelay = 1000 //TODO should this default be overideable from the devicedefinition or it's attributes?
            )
        {
            _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);
            _token       = _tokenSource.Token;

            _adapter = adapter;
            _device  = device;
            _minimumTrasmissionDelay = minimumTrasmissionDelay;

            Task?messageReceiver    = null;
            Task?messageTransmitter = null;
            Task?deviceInitializer  = null;

            var mre = new AsyncManualResetEvent();

            if (_device is IDeviceDefinitionInitialize)
            {
                mre.Reset();
                deviceInitializer = Initializer(mre);
            }
            else
            {
                //Assumed to start in set state but just be sure anyway
                mre.Set();
            }

            if (_device is IDeviceDefinitionReceiver <TMessage> receiver)
            {
                _decoder          = receiver.Decoder;
                _segmentDefintion = receiver.SegmentDefintion;
                messageReceiver   = Receiver(mre);
            }
            if (_device is IDeviceDefinitionTransmitter <TMessage> transmitter)
            {
                _encoder           = transmitter.Encoder;
                messageTransmitter = Transmitter(mre);
            }

            Runner = Task.WhenAll(
                deviceInitializer ?? Task.FromResult(0),
                messageReceiver ?? Task.FromResult(0),
                messageTransmitter ?? Task.FromResult(0)
                );
        }
Exemple #22
0
        public static string TaskScheduler_UnobservedTaskExceptionMsg(object?p_sender, UnobservedTaskExceptionEventArgs p_e)
        {
            Task?senderTask = (p_sender != null) ? null : p_sender as Task;

            if (senderTask != null)
            {
                string msg = $"Sender is a task. TaskId: {senderTask.Id}, IsCompleted: {senderTask.IsCompleted}, IsCanceled: {senderTask.IsCanceled}, IsFaulted: {senderTask.IsFaulted}, TaskToString(): {senderTask.ToString()}.";
                msg += (senderTask.Exception == null) ? " SenderTask.Exception is null" : $" SenderTask.Exception {senderTask.Exception.ToStringWithShortenedStackTrace(1600)}";
                return(msg);
            }
            else
            {
                return("Sender is not a task.");
            }
        }
Exemple #23
0
        public void Start()
        {
            var now = DateTime.Now;

            batches = Assembly.GetExecutingAssembly()
                      .GetTypes()
                      .Where(x => !x.IsInterface && !x.IsAbstract)
                      .Where(x => typeof(IBatch).IsAssignableFrom(x))
                      .Select(x => Activator.CreateInstance(x) as IBatch)
                      .Where(x => x != null)
                      .Select(x => new ScheduledBatch(x !, now))
                      .ToHashSet(ScheduledBatchEqualityComparer.Default);

            task = Task.Run(RunShedulerAsync);
        }
Exemple #24
0
        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            // Store the task we're executing
            _executingTask = ExecuteAsync(_stoppingCts.Token);

            // If the task is completed then return it,
            // this will bubble cancellation and failure to the caller
            if (_executingTask.IsCompleted)
            {
                return(_executingTask);
            }

            // Otherwise it's running
            return(Task.CompletedTask);
        }
Exemple #25
0
 public async Task CloseAsync()
 {
     tokenSource.Cancel();
     if (SerialReadLoopLoop != null)
     {
         await SerialReadLoopLoop;
         SerialReadLoopLoop = null;
     }
     if (PipelineReadLoop != null)
     {
         await PipelineReadLoop;
         PipelineReadLoop = null;
     }
     await spikeConnection.CloseAsync();
 }
Exemple #26
0
 private void StartFetchingServers()
 {
     lock ( listLock )
     {
         // if the server list has been populated, no need to perform any additional work
         if (servers.Count > 0)
         {
             listTask = Task.CompletedTask;
         }
         else if (listTask == null || listTask.IsFaulted || listTask.IsCanceled)
         {
             listTask = ResolveServerList();
         }
     }
 }
        public IMetricServer Start()
        {
            if (_task != null)
            {
                throw new InvalidOperationException("The metric server has already been started.");
            }

            if (_cts == null)
            {
                throw new InvalidOperationException("The metric server has already been started and stopped. Create a new server if you want to start it again.");
            }

            _task = StartServer(_cts.Token);
            return(this);
        }
Exemple #28
0
        private void ChangeToShuttingDown(string reason)
        {
            if (_state == State.ShuttingDown)
            {
                return;
            }

            CompilerServerLogger.Log($"Shutting down server: {reason}");
            Debug.Assert(_state == State.Running);
            Debug.Assert(_clientConnectionHost.IsListening);

            _state       = State.ShuttingDown;
            _timeoutTask = null;
            _gcTask      = null;
        }
Exemple #29
0
        public Task ReturnThenPushSequence(IObserver <int> observer)
        {
            this.FireAndForgetTask = Task.Run(async delegate
            {
                for (int i = 1; i <= 3; i++)
                {
                    observer.OnNext(i);
                    await Task.Yield();
                }

                observer.OnCompleted();
            });

            return(Task.CompletedTask);
        }
Exemple #30
0
        // <summary>
        /// Blocks while condition is true or timeout occurs.
        /// </summary>
        /// <param name="condition">The condition that will perpetuate the block.</param>
        /// <param name="frequency">The frequency at which the condition will be check, in milliseconds.</param>
        /// <param name="timeout">Timeout in milliseconds.</param>
        /// <exception cref="TimeoutException"></exception>
        /// <returns></returns>
        public static async Task WaitWhile(Func <bool> condition, int frequency = 25, int timeout = -1)
        {
            Task?waitTask = Task.Run(async() =>
            {
                while (condition())
                {
                    await Task.Delay(frequency);
                }
            });

            if (waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
            {
                throw new TimeoutException();
            }
        }
Exemple #31
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                timerCancellation.Dispose();
                heartbeatTask = null;

                // cancel replication queue
                replicationQueue.TrySetException(new InvalidOperationException(ExceptionMessages.LocalNodeNotLeader));

                Metrics = null;
            }

            base.Dispose(disposing);
        }