System.Threading.Tasks.TaskCompletionSource.TrySetResult(bool)

Here are the examples of the csharp api System.Threading.Tasks.TaskCompletionSource.TrySetResult(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

611 Examples 7

19 View Source File : AsyncSequence.cs
License : MIT License
Project Creator : Andrew-Hanlon

void IAsyncSequenceProducer<T>.Return(T value)
        {
            _valueQueue.Enqueue(value);
            _nextSource?.TrySetResult(true);
        }

19 View Source File : AmqpConnection.cs
License : Apache License 2.0
Project Creator : apache

internal void OnRemoteOpened(Open open)
        {
            if (SymbolUtil.CheckAndCompareFields(open.Properties, SymbolUtil.CONNECTION_ESTABLISH_FAILED, SymbolUtil.BOOLEAN_TRUE))
            {
                Tracer.InfoFormat("Open response contains {0} property the connection {1} will soon be closed.",
                    SymbolUtil.CONNECTION_ESTABLISH_FAILED, Info.Id);
            }
            else
            {
                Symbol[] capabilities = open.OfferedCapabilities;
                if (capabilities != null)
                {
                    if (Array.Exists(capabilities,
                        symbol => Equals(symbol, SymbolUtil.OPEN_CAPABILITY_ANONYMOUS_RELAY)))
                    {
                        Info.AnonymousRelaySupported = true;
                    }

                    if (Array.Exists(capabilities,
                        symbol => Equals(symbol, SymbolUtil.OPEN_CAPABILITY_DELAYED_DELIVERY)))
                    {
                        Info.DelayedDeliverySupported = true;
                    }

                    if (Array.Exists(capabilities,
                        symbol => Equals(symbol, SymbolUtil.OPEN_CAPABILITY_SHARED_SUBS)))
                    {
                        Info.SharedSubsSupported = true;
                    }
                }



                object value = SymbolUtil.GetFromFields(open.Properties, SymbolUtil.CONNECTION_PROPERTY_TOPIC_PREFIX);
                if (value is string topicPrefix)
                {
                    Info.TopicPrefix = topicPrefix;
                }

                value = SymbolUtil.GetFromFields(open.Properties, SymbolUtil.CONNECTION_PROPERTY_QUEUE_PREFIX);
                if (value is string queuePrefix)
                {
                    Info.QueuePrefix = queuePrefix;
                }
                this.tsc.TrySetResult(true);
                Provider.FireConnectionEstablished();
            }
        }

19 View Source File : TakeUntil.cs
License : Apache License 2.0
Project Creator : akarnokd

private void HandleMain(Task<bool> t, TaskCompletionSource<bool> newTask)
            {
                if (Interlocked.Decrement(ref _disposeMain) != 0)
                {
                    Dispose(_source);
                } 
                else if (t.IsCanceled)
                {
                    newTask.TrySetCanceled();
                    _cancelOther.Cancel();
                }
                else if (t.IsFaulted)
                {
                    newTask.TrySetException(ExceptionHelper.Extract(t.Exception));
                    _cancelOther.Cancel();
                }
                else
                {
                    newTask.TrySetResult(t.Result);
                    if (!t.Result)
                    {
                        _cancelOther.Cancel();
                    }
                }
            }

19 View Source File : TaskLikeObservable.cs
License : MIT License
Project Creator : Andrew-Hanlon

public IDisposable Subscribe(IObserver<T> observer)
        {
            var ret = _subject.Subscribe(observer);

            _subscribeTask.TrySetResult(true);

            return ret;
        }

19 View Source File : ModbusClient.cs
License : MIT License
Project Creator : AndreasAmMueller

private async Task Reconnect()
		{
			try
			{
				logger?.LogTrace("ModbusClient.Reconnect enter");
				lock (reconnectLock)
				{
					if (isReconnecting || stopCts.IsCancellationRequested)
						return;

					isReconnecting = true;
					IsConnected = false;
				}

				logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")} starting.");
				if (wasConnected)
					Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();

				sendCts?.Cancel();
				await sendTask;
				sendCts = null;

				int timeout = 2;
				int maxTimeout = 30;
				var startTime = DateTime.UtcNow;

				using (stopCts.Token.Register(() => reconnectTcs.TrySetCanceled()))
				{
					while (!stopCts.IsCancellationRequested)
					{
						try
						{
							serialPort?.Dispose();

							serialPort = new SerialPort(PortName)
							{
								BaudRate = (int)BaudRate,
								DataBits = DataBits,
								Parity = Parity,
								StopBits = StopBits,
								Handshake = Handshake,
								ReadTimeout = (int)ReceiveTimeout.TotalMilliseconds,
								WriteTimeout = (int)SendTimeout.TotalMilliseconds
							};

							if (bufferSize > 0)
							{
								serialPort.ReadBufferSize = bufferSize;
								serialPort.WriteBufferSize = bufferSize;
							}

							var task = Task.Run(() => serialPort.Open());
							if (await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(timeout), stopCts.Token)) == task)
							{
								if (serialPort.IsOpen)
								{
									lock (reconnectLock)
									{
										IsConnected = true;
										wasConnected = true;

										reconnectTcs?.TrySetResult(true);
										Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
									}
									logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")}ed successfully.");

									sendCts = new CancellationTokenSource();
									sendTask = Task.Run(async () => await ProcessSendQueue());
									return;
								}
								else
								{
									logger?.LogError($"{(wasConnected ? "Reconnect" : "Connect")} failed: Could not open serial port {serialPort.PortName}.");
									reconnectTcs?.TrySetException((Exception)task.Exception ?? new IOException("Serial port not opened."));
									return;
								}
							}
							else if (stopCts.IsCancellationRequested)
							{
								logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")} cancelled.");
								return;
							}
							else
							{
								logger?.LogWarning($"{(wasConnected ? "Reconnect" : "Connect")} failed within {timeout} seconds.");
								timeout += 2;
								if (timeout > maxTimeout)
									timeout = maxTimeout;

								throw new IOException();
							}
						}
						catch (IOException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow <= startTime + ReconnectTimeSpan)
						{
							await Task.Delay(1000, stopCts.Token);
							continue;
						}
						catch (Exception ex)
						{
							logger?.LogError(ex, "ModbusClient.Reconnect failed");
							reconnectTcs?.TrySetException(ex);
							return;
						}
					}
				}
			}
			catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
			{
				// Client shutting down
				return;
			}
			finally
			{
				lock (reconnectLock)
				{
					isReconnecting = false;
					reconnectTcs = null;
				}
				logger?.LogTrace("ModbusClient.Reconnect leave");
			}
		}

19 View Source File : ToObservableTest.cs
License : Apache License 2.0
Project Creator : akarnokd

public void OnCompleted()
            {
                Completed = true;
                _terminate.TrySetResult(true);
            }

19 View Source File : WorkQueue.cs
License : MIT License
Project Creator : ansel86castro

public static Task WaitOneAsync(WaitHandle waitHandle)
        {
            if (waitHandle == null) throw new ArgumentNullException("waitHandle");

            var tcs = new TaskCompletionSource<bool>();
            var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle,
                delegate { tcs.TrySetResult(true); }, null, -1, true);
            var t = tcs.Task;
            t.ContinueWith(_ => rwh.Unregister(null));
            return t;
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private void FailInitialRateLimitTest(BaseRestRequest request, TaskCompletionSource<bool> ratelimitTcs, bool resetToInitial = false)
        {
            if (ratelimitTcs == null && !resetToInitial)
                return;

            var bucket = request.RateLimitBucket;

            bucket._limitValid = false;
            bucket._limitTestFinished = null;
            bucket._limitTesting = 0;

            //Reset to initial values.
            if (resetToInitial)
            {
                this.UpdateHashCaches(request, bucket);
                bucket.Maximum = 0;
                bucket._remaining = 0;
                return;
            }

            // no need to wait on all the potentially waiting tasks
            _ = Task.Run(() => ratelimitTcs.TrySetResult(false));
        }

19 View Source File : UserDialogs.cs
License : Apache License 2.0
Project Creator : AppRopio

public async Task Error(string message)
        {
            CheckNotificationExist();

            var tcs = new TaskCompletionSource<bool>();

            _notificationViewHidden = false;

            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                _notificationView = new ARNotificationView(message, ARNotificationType.Error);
                _notificationView.Show(() => tcs.TrySetResult(true));            
            });

            _notificationViewHidden = await tcs.Task;
        }

19 View Source File : AsyncManualResetEvent.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public Task SetAsync()
            => Task.Run(() => this._resetTcs.TrySetResult(true));

19 View Source File : CoopTask.cs
License : MIT License
Project Creator : Andrew-Hanlon

Task ICoopTaskProducer.Break()
        {
            IsCompleted = true;
            _nextSource.TrySetResult(false);
            return new TaskCompletionSource<bool>().Task;
        }

19 View Source File : ModbusClient.cs
License : MIT License
Project Creator : AndreasAmMueller

private async Task Reconnect()
		{
			try
			{
				logger?.LogTrace("ModbusClient.Reconnect enter");
				lock (reconnectLock)
				{
					if (isReconnecting || stopCts.IsCancellationRequested)
						return;

					isReconnecting = true;
					IsConnected = false;
				}

				logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnect starting.");
				if (wasConnected)
				{
					receiveCts?.Cancel();
					await receiveTask;
					receiveCts = null;
					receiveTask = Task.CompletedTask;
					Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
				}

				var timeout = TimeSpan.FromSeconds(2);
				var startTime = DateTime.UtcNow;

				var address = ResolveHost(Host);
				while (!stopCts.IsCancellationRequested)
				{
					try
					{
						stream?.Dispose();
						stream = null;

						tcpClient?.Dispose();
						tcpClient = new TcpClient(address.AddressFamily);

						var connectTask = tcpClient.ConnectAsync(address, Port);
						if (await Task.WhenAny(connectTask, Task.Delay(timeout, stopCts.Token)) == connectTask && tcpClient.Connected)
						{
							SetKeepAlive();
							stream = tcpClient.GetStream();

							receiveCts = new CancellationTokenSource();
							receiveTask = Task.Run(async () => await ReceiveLoop());

							lock (reconnectLock)
							{
								IsConnected = true;
								wasConnected = true;

								reconnectTcs?.TrySetResult(true);
								Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
							}
							logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnected successfully.");
							return;
						}
						else
						{
							if (timeout < MaxConnectTimeout)
							{
								logger?.LogWarning($"{(wasConnected ? "Rec" : "C")}onnect failed within {timeout}.");
								timeout = timeout.Add(TimeSpan.FromSeconds(2));
								if (timeout > MaxConnectTimeout)
									timeout = MaxConnectTimeout;
							}
							throw new SocketException((int)SocketError.TimedOut);
						}
					}
					catch (SocketException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow - startTime <= ReconnectTimeSpan)
					{
						await Task.Delay(1000, stopCts.Token);
						continue;
					}
					catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
					{
						throw;
					}
					catch (Exception ex)
					{
						logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}, trying again.");
					}
				}
			}
			catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
			{
				reconnectTcs?.TrySetCanceled();
			}
			catch (Exception ex)
			{
				logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}");
				reconnectTcs?.TrySetException(ex);
			}
			finally
			{
				lock (reconnectLock)
				{
					isReconnecting = false;
					reconnectTcs = null;
				}
				logger?.LogTrace("ModbusClient.Reconnect leave");
			}
		}

19 View Source File : ResumeHelperTest.cs
License : Apache License 2.0
Project Creator : akarnokd

[Fact]
        public void Value_Success()
        {
            var source = new TaskCompletionSource<bool>();
            source.TrySetResult(true);

            ResumeHelper.Complete(ref _tcs, new ValueTask(source.Task));

            replacedert.True(_tcs.Task.IsCompleted);
            replacedert.True(_tcs.Task.Result);
        }

19 View Source File : AsyncEnumerator.cs
License : MIT License
Project Creator : Andrew-Hanlon

public Task<bool> MoveNextAsync()
        {
            _exception?.Throw();

            if (!_isStarted)
            {
                _isStarted = true;
                return Task.FromResult(true);
            }

            _nextSource = new TaskCompletionSource<bool>();

            _yieldSource?.TrySetResult(true);

            return _yieldSource is null ? Task.FromResult(true) : _nextSource.Task;
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnceOnlyTakeOneJobMessage()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    Ephemeral = true
                };

                var message1 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };
                var message2 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4235,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message1);
                messages.Enqueue(message2);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);

                var runOnceJobCompleted = new TaskCompletionSource<bool>();
                _jobDispatcher.Setup(x => x.RunOnceJobCompleted)
                    .Returns(runOnceJobCompleted);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {
                        runOnceJobCompleted.TrySetResult(true);
                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job and exit
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);

                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
                     $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
            }
        }

19 View Source File : BaseDialogUserControl.cs
License : MIT License
Project Creator : angelsix

public Task ShowDialog<T>(T viewModel)
            where T : BaseDialogViewModel
        {
            // Create a task to await the dialog closing
            var tcs = new TaskCompletionSource<bool>();

            // Run on UI thread
            Application.Current.Dispatcher.Invoke(() =>
            {
                try
                {
                    // Match controls expected sizes to the dialog windows view model
                    mDialogWindow.ViewModel.WindowMinimumWidth = WindowMinimumWidth;
                    mDialogWindow.ViewModel.WindowMinimumHeight = WindowMinimumHeight;
                    mDialogWindow.ViewModel.replacedleHeight = replacedleHeight;
                    mDialogWindow.ViewModel.replacedle = string.IsNullOrEmpty(viewModel.replacedle) ? replacedle : viewModel.replacedle;

                    // Set this control to the dialog window content
                    mDialogWindow.ViewModel.Content = this;

                    // Setup this controls data context binding to the view model
                    DataContext = viewModel;

                    // Show in the center of the parent
                    mDialogWindow.Owner = Application.Current.MainWindow;
                    mDialogWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                    // Show dialog
                    mDialogWindow.ShowDialog();
                }
                finally
                {
                    // Let caller know we finished
                    tcs.TrySetResult(true);
                }
            });

            return tcs.Task;
        }

19 View Source File : ResumeHelper.cs
License : Apache License 2.0
Project Creator : akarnokd

internal static void Resume(ref TaskCompletionSource<bool> field)
        {
            for (; ; )
            {
                var a = Volatile.Read(ref field);
                if (a == null)
                {
                    if (Interlocked.CompareExchange(ref field, ResumeTrue, null) == null)
                    {
                        break;
                    }
                }
                else
                {
                    if (a != ResumeTrue)
                    {
                        a.TrySetResult(true);
                    }
                    break;
                }
            }
        }

19 View Source File : FailoverRequest.cs
License : Apache License 2.0
Project Creator : apache

public async Task Run()
        {
            // Snapshot the current provider as this action is scoped to that
            // instance and any failure we report should reflect the provider
            // that was in use when the failure happened.
            IProvider activeProvider = failoverProvider.ActiveProvider;

            if (activeProvider == null)
            {
                WhenOffline(new IOException("Connection failed."));
            }
            else
            {
                try
                {
                    await this.DoTask(activeProvider).Await();
                    this.taskCompletionSource.TrySetResult(true);
                    this.failoverProvider.RemoveFailoverRequest(this);
                    this.cancellationTokenSource?.Dispose();
                }
                catch (NMSConnectionException exception)
                {
                    Tracer.Debug($"Caught connection exception while executing task: {this} - {exception.Message}");
                    WhenOffline(exception);
                }
                catch (NMSException exception)
                {
                    this.failoverProvider.RemoveFailoverRequest(this);
                    this.taskCompletionSource.TrySetException(exception);
                }
                catch (Exception exception)
                {
                    Tracer.Debug($"Caught exception while executing task: {this} - {exception.Message}");
                    WhenOffline(exception);
                }
            }
        }

19 View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions

public async Task<int> ExecuteAsync(
            string workingDirectory,
            string fileName,
            string arguments,
            IDictionary<string, string> environment,
            bool requireExitCodeZero,
            Encoding outputEncoding,
            bool killProcessOnCancel,
            Channel<string> redirectStandardIn,
            bool inheritConsoleHandler,
            bool keepStandardInOpen,
            bool highPriorityProcess,
            CancellationToken cancellationToken)
        {
            ArgUtil.Null(_proc, nameof(_proc));
            ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));

            Trace.Info("Starting process:");
            Trace.Info($"  File name: '{fileName}'");
            Trace.Info($"  Arguments: '{arguments}'");
            Trace.Info($"  Working directory: '{workingDirectory}'");
            Trace.Info($"  Require exit code zero: '{requireExitCodeZero}'");
            Trace.Info($"  Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
            Trace.Info($"  Force kill process on cancellation: '{killProcessOnCancel}'");
            Trace.Info($"  Redirected STDIN: '{redirectStandardIn != null}'");
            Trace.Info($"  Persist current code page: '{inheritConsoleHandler}'");
            Trace.Info($"  Keep redirected STDIN open: '{keepStandardInOpen}'");
            Trace.Info($"  High priority process: '{highPriorityProcess}'");

            _proc = new Process();
            _proc.StartInfo.FileName = fileName;
            _proc.StartInfo.Arguments = arguments;
            _proc.StartInfo.WorkingDirectory = workingDirectory;
            _proc.StartInfo.UseShellExecute = false;
            _proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
            _proc.StartInfo.RedirectStandardInput = true;
            _proc.StartInfo.RedirectStandardError = true;
            _proc.StartInfo.RedirectStandardOutput = true;

            // Ensure we process STDERR even the process exit event happen before we start read STDERR stream. 
            if (_proc.StartInfo.RedirectStandardError)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

#if OS_WINDOWS
            // If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
            // ProcessStartInfo object, then .NET PInvokes to resolve the default console output
            // code page:
            //      [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
            //      public extern static uint GetConsoleOutputCP();
            StringUtil.EnsureRegisterEncodings();
#endif
            if (outputEncoding != null)
            {
                _proc.StartInfo.StandardErrorEncoding = outputEncoding;
                _proc.StartInfo.StandardOutputEncoding = outputEncoding;
            }

            // Copy the environment variables.
            if (environment != null && environment.Count > 0)
            {
                foreach (KeyValuePair<string, string> kvp in environment)
                {
                    _proc.StartInfo.Environment[kvp.Key] = kvp.Value;
                }
            }

            // Indicate GitHub Actions process.
            _proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
                Environment.GetEnvironmentVariable("CI") == null)
            {
                _proc.StartInfo.Environment["CI"] = "true";
            }

            // Hook up the events.
            _proc.EnableRaisingEvents = true;
            _proc.Exited += ProcessExitedHandler;

            // Start the process.
            _stopWatch = Stopwatch.StartNew();
            _proc.Start();

            // Decrease invoked process priority, in platform specifc way, relative to parent
            if (!highPriorityProcess)
            {
                DecreaseProcessPriority(_proc);
            }

            // Start the standard error notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardError)
            {
                StartReadStream(_proc.StandardError, _errorData);
            }

            // Start the standard output notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                StartReadStream(_proc.StandardOutput, _outputData);
            }

            if (_proc.StartInfo.RedirectStandardInput)
            {
                if (redirectStandardIn != null)
                {
                    StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
                }
                else
                {
                    // Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
                    _proc.StandardInput.Close();
                }
            }

            var cancellationFinished = new TaskCompletionSource<bool>();
            using (var registration = cancellationToken.Register(async () =>
            {
                await CancelAndKillProcessTree(killProcessOnCancel);
                cancellationFinished.TrySetResult(true);
            }))
            {
                Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
                while (true)
                {
                    Task outputSignal = _outputProcessEvent.WaitAsync();
                    var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);

                    if (signaled == outputSignal)
                    {
                        ProcessOutput();
                    }
                    else
                    {
                        _stopWatch.Stop();
                        break;
                    }
                }

                // Just in case there was some pending output when the process shut down go ahead and check the
                // data buffers one last time before returning
                ProcessOutput();

                if (cancellationToken.IsCancellationRequested)
                {
                    // Ensure cancellation also finish on the cancellationToken.Register thread.
                    await cancellationFinished.Task;
                    Trace.Info($"Process Cancellation finished.");
                }

                Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Wait for process to finish.
            if (_proc.ExitCode != 0 && requireExitCodeZero)
            {
                throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
            }

            return _proc.ExitCode;
        }

19 View Source File : UserDialogs.cs
License : Apache License 2.0
Project Creator : AppRopio

public async Task<bool> Confirm(string message, string buttonreplacedle, bool autoHide)
        {
            CheckNotificationExist();

            var tcs = new TaskCompletionSource<bool>();

            _notificationViewHidden = false;

            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                _notificationView = new ARNotificationView(message, ARNotificationType.Confirm, buttonreplacedle, autoHide);
                _notificationView.Show(() => tcs.TrySetResult(false), () => tcs.SetResult(true));
            });

            var result = await tcs.Task;

            _notificationViewHidden = true;

            return result;
        }

19 View Source File : Timeout.cs
License : Apache License 2.0
Project Creator : akarnokd

private void Next(long idx, Task<bool> task, TaskCompletionSource<bool> result)
            {
                if (Interlocked.Decrement(ref _disposeWip) != 0)
                {
                    DisposeTask();
                }
                if (Interlocked.CompareExchange(ref _index, idx + 1, idx) == idx)
                {
                    _token?.Cancel();
                    if (task.IsCanceled)
                    {
                        result.TrySetCanceled();
                    }
                    else if (task.IsFaulted)
                    {
                        result.TrySetException(ExceptionHelper.Extract(task.Exception));
                    }
                    else
                    {
                        result.TrySetResult(task.Result);
                    }
                }
            }

19 View Source File : TestTaskRunner.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Signal()
            {
                try
                {
                    _action();
                    _tcs.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    _tcs.TrySetException(ex);
                }
            }

19 View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions

private void ProcessExitedHandler(object sender, EventArgs e)
        {
            if ((_proc.StartInfo.RedirectStandardError || _proc.StartInfo.RedirectStandardOutput) && _asyncStreamReaderCount != 0)
            {
                _waitingOnStreams = true;

                Task.Run(async () =>
                {
                    // Wait 5 seconds and then Cancel/Kill process tree
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    KillProcessTree();
                    _processExitedCompletionSource.TrySetResult(true);
                    _processStandardInWriteCancellationTokenSource.Cancel();
                });
            }
            else
            {
                _processExitedCompletionSource.TrySetResult(true);
                _processStandardInWriteCancellationTokenSource.Cancel();
            }
        }

19 View Source File : ModbusClient.cs
License : MIT License
Project Creator : AndreasAmMueller

private void DisconnectInternal()
		{
			try
			{
				logger?.LogTrace("ModbusClient.DisconnectInternal enter");

				if (!isStarted)
					return;

				try
				{
					stopCts?.Cancel();
					reconnectTcs?.TrySetResult(false);
					reconnectTcs = null;
				}
				catch
				{ }

				try
				{
					sendCts?.Cancel();
					lock (queueLock)
					{
						foreach (var task in sendQueue)
						{
							task.TaskCompletionSource.TrySetCanceled();
							task.Registration.Dispose();
						}
						sendQueue.Clear();
					}
				}
				catch
				{ }

				bool connected = false;
				lock (reconnectLock)
				{
					connected = IsConnected;
					IsConnected = false;
					wasConnected = false;
				}

				try
				{
					serialPort?.Close();
					serialPort?.Dispose();
					serialPort = null;
				}
				catch
				{ }

				if (connected)
					Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();

				isStarted = false;

				if (driverModified)
				{
					try
					{
						var rs485 = GetDriverState();
						rs485.Flags = serialDriverFlags;
						SetDriverState(rs485);
						driverModified = false;
					}
					catch (Exception ex)
					{
						logger?.LogError(ex, "ModbusClient.Disconnect failed to reset the serial driver state.");
						throw;
					}
				}
			}
			finally
			{
				logger?.LogTrace("ModbusClient.DisconnectInternal leave");
			}
		}

19 View Source File : AsyncManualResetEvent.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public Task SetAsync() => Task.Run(() => this._tsc.TrySetResult(true));

19 View Source File : CoopTask.cs
License : MIT License
Project Creator : Andrew-Hanlon

internal override void SetCompletion()
        {
            IsCompleted = true;
            _nextSource.TrySetResult(false);
        }

19 View Source File : AsyncEnumerator.cs
License : MIT License
Project Creator : Andrew-Hanlon

T IAsyncEnumeratorProducer<T>.Break()
        {
            IsCompleted = true;
            _nextSource.TrySetResult(false);
            return default(T);
        }

19 View Source File : QueueDrainHelper.cs
License : Apache License 2.0
Project Creator : akarnokd

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal static void DisposeOne(ref int allDisposeWip, ref Exception allDisposeError, TaskCompletionSource<bool> allDisposeTask)
        {
            if (Interlocked.Decrement(ref allDisposeWip) == 0)
            {
                var ex = allDisposeError;
                if (ex != null)
                {
                    allDisposeError = null;
                    allDisposeTask.TrySetException(ex);
                }
                else
                {
                    allDisposeTask.TrySetResult(true);
                }
            }
        }

19 View Source File : CoopTask.cs
License : MIT License
Project Creator : Andrew-Hanlon

Task ICoopTaskProducer.Yield()
        {
            _yieldSource = new TaskCompletionSource<bool>();

            _nextSource?.TrySetResult(true);

            return _yieldSource.Task;
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnce()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    Ephemeral = true
                };

                var message = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);

                var runOnceJobCompleted = new TaskCompletionSource<bool>();
                _jobDispatcher.Setup(x => x.RunOnceJobCompleted)
                    .Returns(runOnceJobCompleted);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {
                        runOnceJobCompleted.TrySetResult(true);
                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job and exit
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);

                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
                     $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());

                // verify that we did try to delete local settings file (since we're ephemeral)
                _configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Once());
            }
        }

19 View Source File : AsyncEnumerator.cs
License : MIT License
Project Creator : Andrew-Hanlon

Task IAsyncEnumeratorProducer<T>.Return(T value)
        {
            Current = value;

            _yieldSource = new TaskCompletionSource<bool>();

            _nextSource?.TrySetResult(true);

            return _yieldSource.Task;
        }

19 View Source File : ResumeHelperTest.cs
License : Apache License 2.0
Project Creator : akarnokd

[Fact]
        public async void Async_Success()
        {
            var source = new TaskCompletionSource<bool>();

            ResumeHelper.Complete(ref _tcs, new ValueTask(source.Task));

            source.TrySetResult(true);

            await _tcs.Task;
            
            replacedert.True(_tcs.Task.IsCompleted);
            replacedert.True(_tcs.Task.Result);
        }

19 View Source File : AsyncSequence.cs
License : MIT License
Project Creator : Andrew-Hanlon

T IAsyncSequenceProducer<T>.Break()
        {
            IsCompleted = true;
            _nextSource?.TrySetResult(false);
            return default(T);
        }

19 View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions

public void Set()
            {
                var tcs = m_tcs;
                Task.Factory.StartNew(s => ((TaskCompletionSource<bool>)s).TrySetResult(true),
                    tcs, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default);
                tcs.Task.Wait();
            }

19 View Source File : WaitHandleExtensions.cs
License : MIT License
Project Creator : angelsix

public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken? cancellationToken)
        {
            // Create a handle that awaiting the original wait handle
            RegisteredWaitHandle registeredWaitHandle = null;

            // Store the token 
            CancellationTokenRegistration? tokenRegistration = null;

            try
            {
                // Create a task completion source to await
                var tcs = new TaskCompletionSource<bool>();

                // Use RegisterWaitForSingleObject so we get a callback
                // once the wait handle has finished, and set the tcs result in that callback
                registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                    // The handle to wait on
                    handle, 
                    // When it is finished, set the tcs result
                    (state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
                    // Preplaced the tcs as the state so we don't have a reference to the parent tcs (optimization)
                    tcs,
                    // Set timeout if preplaceded in
                    millisecondsTimeout,
                    // Run once don't keep resetting timeout
                    true);

                // Register to run the action and set the tcs as canceled
                // if the cancellation token itself is canceled
                // which will throw a TaskCanceledException up to the caller
                if (cancellationToken.HasValue)
                    tokenRegistration = cancellationToken.Value.Register(state => ((TaskCompletionSource<bool>)state).TrySetCanceled(), tcs);

                // Await the handle or the cancellation token
                return await tcs.Task;
            }
            finally
            {
                // Clean up registered wait handle
                registeredWaitHandle?.Unregister(null);

                // Dispose of the token we had to create to register for the cancellation token callback
                tokenRegistration?.Dispose();
            }
        }

19 View Source File : ToObservableTest.cs
License : Apache License 2.0
Project Creator : akarnokd

public void OnError(Exception error)
            {
                Error = error;
                _terminate.TrySetResult(true);
            }

19 View Source File : UsbManagerExtensions.cs
License : GNU Lesser General Public License v2.1
Project Creator : anotherlab

public override void OnReceive(Context context, Intent intent)
            {
                var device = intent.GetParcelableExtra(UsbManager.ExtraDevice) as UsbDevice;
                var permissionGranted = intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false);
                context.UnregisterReceiver(this);
                completionSource.TrySetResult(permissionGranted);
            }

19 View Source File : AsyncConnector.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

void InitConnection()
        {
            if (_connectionTaskSource != null)
                _connectionTaskSource.TrySetResult(false);

            _connectionTaskSource = new TaskCompletionSource<bool>();
        }

19 View Source File : AmqpConnectionSession.cs
License : Apache License 2.0
Project Creator : apache

public async Task Unsubscribe(string subscriptionName)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

            ReceiverLink receiverLink = new ReceiverLink(UnderlyingSession, subscriptionName, CreateAttach(subscriptionName), (link, attach) =>
            {
                Tracer.InfoFormat("Attempting to close subscription {0}. Attach response {1}", subscriptionName, attach);
                if (attach.Source is Source source)
                {
                    Tracer.InfoFormat("Found subscription {0} on remote with source {1}.", subscriptionName, source);
                    tcs.TrySetResult(true);
                }
            });
            receiverLink.AddClosedCallback((sender, error) =>
            {
                string failureMessage = string.Equals(sender.Error?.Condition, ErrorCode.NotFound)
                    ? $"Cannot remove Subscription {subscriptionName} that does not exists"
                    : $"Subscription {subscriptionName} unsubscribe operation failure";

                if (!tcs.Task.IsCompleted || error != null)
                {
                    NMSException exception = ExceptionSupport.GetException(sender, failureMessage);
                    tcs.TrySetException(exception);
                }
            });

            await tcs.Task.Await();
            
            await receiverLink.CloseAsync(TimeSpan.FromMilliseconds(Connection.Provider.CloseTimeout)).AwaitRunContinuationAsync();
        }

19 View Source File : ResumeHelper.cs
License : Apache License 2.0
Project Creator : akarnokd

internal static void Complete(ref TaskCompletionSource<bool> field, ValueTask task)
        {
            var tcs = GetOrCreate(ref field);

            if (task.IsCanceled)
            {
                tcs.TrySetCanceled();
            }
            else
            if (task.IsFaulted)
            {
                tcs.TrySetException(task.AsTask().Exception);
            }
            else
            if (task.IsCompleted)
            {
                tcs.TrySetResult(true);
            }
            else
            {
                task.AsTask()
                    .ContinueWith(Completer, 
                        tcs, 
                        TaskContinuationOptions.ExecuteSynchronously
                    );
            }
        }

19 View Source File : AmqpSession.cs
License : Apache License 2.0
Project Creator : apache

public Task Start()
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

            var requestTimeout = Connection.Provider.RequestTimeout;
            if (requestTimeout > 0)
            {
                CancellationTokenSource ct = new CancellationTokenSource(TimeSpan.FromMilliseconds(requestTimeout));
                ct.Token.Register(() => tcs.TrySetCanceled(), false);
            }

            UnderlyingSession = new Session(Connection.UnderlyingConnection, CreateBeginFrame(),
                (session, begin) =>
                {
                    tcs.TrySetResult(true);
                });
            UnderlyingSession.AddClosedCallback((sender, error) =>
            {
                if (!tcs.TrySetException(ExceptionSupport.GetException(error)))
                {
                    Connection.RemoveSession(SessionInfo.Id);
                }
            });
            return tcs.Task;
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : actions

public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (cancellationToken.Register(
                        s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
                if (task != await Task.WhenAny(task, tcs.Task))
                    throw new OperationCanceledException(cancellationToken);
            await task;
        }

19 View Source File : UserDialogs.cs
License : Apache License 2.0
Project Creator : AppRopio

public async Task Alert(string message)
        {
            CheckNotificationExist();

            var tcs = new TaskCompletionSource<bool>();

            _notificationViewHidden = false;

            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                _notificationView = new ARNotificationView(message, ARNotificationType.Alert);
                _notificationView.Show(() => tcs.TrySetResult(true));
            });

            _notificationViewHidden = await tcs.Task;
        }

19 View Source File : TakeUntil.cs
License : Apache License 2.0
Project Creator : akarnokd

private void HandleOther(Task t)
            {
                if (Interlocked.Decrement(ref _disposeOther) != 0)
                {
                    Dispose(_other);
                }
                else if (t.IsCanceled)
                {
                    _otherError = new OperationCanceledException();
                    var oldTask = Interlocked.Exchange(ref _currentTask, TakeUntilHelper.UntilTask);
                    _cancelMain.Cancel();
                    if (oldTask != TakeUntilHelper.UntilTask)
                    {
                        oldTask?.TrySetCanceled();
                    }
                }
                else if (t.IsFaulted) {
                    _otherError = ExceptionHelper.Extract(t.Exception);
                    var oldTask = Interlocked.Exchange(ref _currentTask, TakeUntilHelper.UntilTask);
                    _cancelMain.Cancel();
                    if (oldTask != TakeUntilHelper.UntilTask)
                    {
                        oldTask?.TrySetException(t.Exception);
                    }
                }
                else
                {
                    var oldTask = Interlocked.Exchange(ref _currentTask, TakeUntilHelper.UntilTask);
                    _cancelMain.Cancel();
                    if (oldTask != TakeUntilHelper.UntilTask)
                    {
                        if (Interlocked.Increment(ref _disposeMain) == 1)
                        {
                            Dispose(_source);
                        }
                        if (Interlocked.Increment(ref _disposeOther) == 1)
                        {
                            Dispose(_other);
                        }
                        oldTask?.TrySetResult(false);
                    }
                }
            }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private void UpdateBucket(BaseRestRequest request, RestResponse response, TaskCompletionSource<bool> ratelimitTcs)
        {
            var bucket = request.RateLimitBucket;

            if (response.Headers == null)
            {
                if (response.ResponseCode != 429) // do not fail when ratelimit was or the next request will be scheduled hitting the rate limit again
                    this.FailInitialRateLimitTest(request, ratelimitTcs);
                return;
            }

            var hs = response.Headers;

            if (hs.TryGetValue("X-RateLimit-Global", out var isglobal) && isglobal.ToLowerInvariant() == "true")
            {
                if (response.ResponseCode != 429)
                    this.FailInitialRateLimitTest(request, ratelimitTcs);

                return;
            }

            var r1 = hs.TryGetValue("X-RateLimit-Limit", out var usesmax);
            var r2 = hs.TryGetValue("X-RateLimit-Remaining", out var usesleft);
            var r3 = hs.TryGetValue("X-RateLimit-Reset", out var reset);
            var r4 = hs.TryGetValue("X-Ratelimit-Reset-After", out var resetAfter);
            var r5 = hs.TryGetValue("X-Ratelimit-Bucket", out var hash);

            if (!r1 || !r2 || !r3 || !r4)
            {
                //If the limits were determined before this request, make the bucket initial again.
                if (response.ResponseCode != 429)
                    this.FailInitialRateLimitTest(request, ratelimitTcs, ratelimitTcs == null);

                return;
            }

            var clienttime = DateTimeOffset.UtcNow;
            var resettime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(double.Parse(reset, CultureInfo.InvariantCulture));
            var servertime = clienttime;
            if (hs.TryGetValue("Date", out var raw_date))
                servertime = DateTimeOffset.Parse(raw_date, CultureInfo.InvariantCulture).ToUniversalTime();

            var resetdelta = resettime - servertime;
            //var difference = clienttime - servertime;
            //if (Math.Abs(difference.TotalSeconds) >= 1)
            ////    this.Logger.LogMessage(LogLevel.DebugBaseDiscordClient.RestEventId,  $"Difference between machine and server time: {difference.TotalMilliseconds.ToString("#,##0.00", CultureInfo.InvariantCulture)}ms", DateTime.Now);
            //else
            //    difference = TimeSpan.Zero;

            if (request.RateLimitWaitOverride.HasValue)
                resetdelta = TimeSpan.FromSeconds(request.RateLimitWaitOverride.Value);
            var newReset = clienttime + resetdelta;

            if (this.UseResetAfter)
            {
                bucket.ResetAfter = TimeSpan.FromSeconds(double.Parse(resetAfter, CultureInfo.InvariantCulture));
                newReset = clienttime + bucket.ResetAfter.Value + (request.RateLimitWaitOverride.HasValue
                    ? resetdelta
                    : TimeSpan.Zero);
                bucket.ResetAfterOffset = newReset;
            }
            else
                bucket.Reset = newReset;

            var maximum = int.Parse(usesmax, CultureInfo.InvariantCulture);
            var remaining = int.Parse(usesleft, CultureInfo.InvariantCulture);

            if (ratelimitTcs != null)
            {
                // initial population of the ratelimit data
                bucket.SetInitialValues(maximum, remaining, newReset);

                _ = Task.Run(() => ratelimitTcs.TrySetResult(true));
            }
            else
            {
                // only update the bucket values if this request was for a newer interval than the one
                // currently in the bucket, to avoid issues with concurrent requests in one bucket
                // remaining is reset by TryResetLimit and not the response, just allow that to happen when it is time
                if (bucket._nextReset == 0)
                    bucket._nextReset = newReset.UtcTicks;
            }

            this.UpdateHashCaches(request, bucket, hash);
        }

19 View Source File : RedisSocket.cs
License : MIT License
Project Creator : 2881099

public Task<bool> ConnectAsync(EndPoint endpoint)
        {
            InitSocket(endpoint);

            if (connectTcs != null) connectTcs.TrySetCanceled();
            connectTcs = new TaskCompletionSource<bool>();

            _socket.BeginConnect(endpoint, asyncResult =>
            {
                try
                {
                    _socket.EndConnect(asyncResult);
                    connectTcs.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    connectTcs.TrySetException(ex);
                }
            }, null);
            return connectTcs.Task;
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : actions

public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (cancellationToken.Register(
                        s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
                if (task != await Task.WhenAny(task, tcs.Task))
                    throw new OperationCanceledException(cancellationToken);
            return await task;
        }

19 View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions

private void StartReadStream(StreamReader reader, ConcurrentQueue<string> dataBuffer)
        {
            Task.Run(() =>
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line != null)
                    {
                        dataBuffer.Enqueue(line);
                        _outputProcessEvent.Set();
                    }
                }

                Trace.Info("STDOUT/STDERR stream read finished.");

                if (Interlocked.Decrement(ref _asyncStreamReaderCount) == 0 && _waitingOnStreams)
                {
                    _processExitedCompletionSource.TrySetResult(true);
                    _processStandardInWriteCancellationTokenSource.Cancel();
                }
            });
        }

19 View Source File : InteractionPaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal void RegenerateCTS(DiscordInteraction interaction)
        {
            this._interactionCts?.Dispose();
            this._lastInteraction = interaction;
            this._interactionCts = new(TimeSpan.FromSeconds((60 * 15) - 5));
            this._interactionCts.Token.Register(() => this._tcs.TrySetResult(false));
        }

19 View Source File : CoopTask.cs
License : MIT License
Project Creator : Andrew-Hanlon

public Task<bool> MoveNextAsync()
        {
            _exception?.Throw();

            if (!_isStarted)
            {
                _isStarted = true;
                return Task.FromResult(true);
            }

            _nextSource = new TaskCompletionSource<bool>();

            _yieldSource?.TrySetResult(true);

            return _yieldSource == null ? Task.FromResult(true) : _nextSource.Task;
        }

See More Examples