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 Source : OutboundCallReminder.cs
with MIT License
from Azure-Samples

private void RegisterToCallStateChangeEvent(string callConnectionId)
        {
            callEstablishedTask = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
            reportCancellationToken.Register(() => callEstablishedTask.TrySetCanceled());

            callTerminatedTask = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);

            //Set the callback method
            var callStateChangeNotificaiton = new NotificationCallback((CallingServerEventBase callEvent) =>
            {
                var callStateChanged = (CallConnectionStateChangedEvent)callEvent;

                Logger.LogMessage(Logger.MessageType.INFORMATION, $"Call State changed to: {callStateChanged.CallConnectionState}");

                if (callStateChanged.CallConnectionState == CallConnectionState.Connected)
                {
                    callEstablishedTask.TrySetResult(true);
                }
                else if (callStateChanged.CallConnectionState == CallConnectionState.Disconnected)
                {
                    EventDispatcher.Instance.Unsubscribe(CallingServerEventType.CallConnectionStateChangedEvent.ToString(), callConnectionId);
                    reportCancellationTokenSource.Cancel();
                    callTerminatedTask.SetResult(true);
                }
            });

            //Subscribe to the event
            var eventId = EventDispatcher.Instance.Subscribe(CallingServerEventType.CallConnectionStateChangedEvent.ToString(), callConnectionId, callStateChangeNotificaiton);
        }

19 Source : OutboundCallReminder.cs
with MIT License
from Azure-Samples

private void RegisterToPlayAudioResultEvent(string operationContext)
        {
            playAudioCompletedTask = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
            reportCancellationToken.Register(() => playAudioCompletedTask.TrySetCanceled());

            var playPromptResponseNotification = new NotificationCallback((CallingServerEventBase callEvent) =>
            {
                Task.Run(() =>
                {
                    var playAudioResultEvent = (PlayAudioResultEvent)callEvent;
                    Logger.LogMessage(Logger.MessageType.INFORMATION, $"Play audio status: {playAudioResultEvent.Status}");

                    if (playAudioResultEvent.Status == OperationStatus.Completed)
                    {
                        playAudioCompletedTask.TrySetResult(true);
                        EventDispatcher.Instance.Unsubscribe(CallingServerEventType.PlayAudioResultEvent.ToString(), operationContext);
                    }
                    else if (playAudioResultEvent.Status == OperationStatus.Failed)
                    {
                        playAudioCompletedTask.TrySetResult(false);
                    }
                });
            });

            //Subscribe to event
            EventDispatcher.Instance.Subscribe(CallingServerEventType.PlayAudioResultEvent.ToString(), operationContext, playPromptResponseNotification);
        }

19 Source : OutboundCallReminder.cs
with MIT License
from Azure-Samples

private void RegisterToDtmfResultEvent(string callConnectionId)
        {
            toneReceivedCompleteTask = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
            var dtmfReceivedEvent = new NotificationCallback((CallingServerEventBase callEvent) =>
            {
                Task.Run(async () =>
                {
                    var toneReceivedEvent = (ToneReceivedEvent)callEvent;
                    Logger.LogMessage(Logger.MessageType.INFORMATION, $"Tone received --------- : {toneReceivedEvent.ToneInfo?.Tone}");

                    if (toneReceivedEvent?.ToneInfo?.Tone == ToneValue.Tone1)
                    {
                        toneReceivedCompleteTask.TrySetResult(true);
                    }
                    else
                    {
                        toneReceivedCompleteTask.TrySetResult(false);
                    }

                    EventDispatcher.Instance.Unsubscribe(CallingServerEventType.ToneReceivedEvent.ToString(), callConnectionId);
                    // cancel playing audio
                    await CancelAllMediaOperations().ConfigureAwait(false);
                });
            });
            //Subscribe to event
            EventDispatcher.Instance.Subscribe(CallingServerEventType.ToneReceivedEvent.ToString(), callConnectionId, dtmfReceivedEvent);
        }

19 Source : OutboundCallReminder.cs
with MIT License
from Azure-Samples

private async Task<bool> AddParticipant(string addedParticipant)
        {
            addParticipantCompleteTask = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);

            var identifierKind = GetIdentifierKind(addedParticipant);

            if (identifierKind == CommunicationIdentifierKind.UnknownIdenreplacedy)
            {
                Logger.LogMessage(Logger.MessageType.INFORMATION, "Unknown idenreplacedy provided. Enter valid phone number or communication user id");
                addParticipantCompleteTask.TrySetResult(true);
            }
            else
            {
                var operationContext = Guid.NewGuid().ToString();

                RegisterToAddParticipantsResultEvent(operationContext);

                if (identifierKind == CommunicationIdentifierKind.UserIdenreplacedy)
                {
                    var response = await callConnection.AddParticipantAsync(new CommunicationUserIdentifier(addedParticipant), null, operationContext).ConfigureAwait(false);
                    Logger.LogMessage(Logger.MessageType.INFORMATION, $"AddParticipantAsync response --> {response}");
                }
                else if (identifierKind == CommunicationIdentifierKind.PhoneIdenreplacedy)
                {
                    var response = await callConnection.AddParticipantAsync(new PhoneNumberIdentifier(addedParticipant), callConfiguration.SourcePhoneNumber, operationContext).ConfigureAwait(false);
                    Logger.LogMessage(Logger.MessageType.INFORMATION, $"AddParticipantAsync response --> {response}");
                }
            }

            var addParticipantCompleted = await addParticipantCompleteTask.Task.ConfigureAwait(false);
            return addParticipantCompleted;
        }

19 Source : ProcessInvoker.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak

private void OnProcessExited(object sender, EventArgs e)
        {

            _trace?.Verbose($"Exited process {_proc.Id} with exit code {_proc.ExitCode}");

            if (_streamReadCount != 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);

                });
            }
            else
            {
                _processExitedCompletionSource.TrySetResult(true);
            }
        }

19 Source : Tools.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak

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 Source : ProcessInvoker.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak

private Task ReadStream(StreamReader reader, ConcurrentQueue<string> dataBuffer)
        {
            return Task.Run(() =>
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();

                    if (line != null)
                    {
                        dataBuffer.Enqueue(line);
                        _outputProcessEvent.Set();

                    }
                }

                _trace?.Verbose("STDOUT/STDERR stream read finished.");

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

19 Source : ConsumerChannelsManager.cs
with MIT License
from BEagle1984

[SuppressMessage("", "CA1031", Justification = Justifications.ExceptionLogged)]
        private async Task ReadChannelAsync(
            int channelIndex,
            ChannelReader<ConsumeResult<byte[]?, byte[]?>> channelReader,
            CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogConsumerLowLevelTrace(
                    _consumer,
                    "Starting channel {channelIndex} processing loop...",
                    () => new object[] { channelIndex });

                while (!cancellationToken.IsCancellationRequested)
                {
                    await ReadChannelOnceAsync(channelReader, channelIndex, cancellationToken)
                        .ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                // Ignore
                _logger.LogConsumerLowLevelTrace(
                    _consumer,
                    "Exiting channel {channelIndex} processing loop (operation canceled).",
                    () => new object[] { channelIndex });
            }
            catch (Exception ex)
            {
                if (ex is not ConsumerPipelineFatalException)
                    _logger.LogConsumerFatalError(_consumer, ex);

                IsReading[channelIndex] = false;
                _readTaskCompletionSources[channelIndex].TrySetResult(false);

                await _consumer.DisconnectAsync().ConfigureAwait(false);
            }

            IsReading[channelIndex] = false;
            _readTaskCompletionSources[channelIndex].TrySetResult(true);

            _logger.LogConsumerLowLevelTrace(
                _consumer,
                "Exited channel {channelIndex} processing loop.",
                () => new object[] { channelIndex });
        }

19 Source : SequenceBase`1.cs
with MIT License
from BEagle1984

void ISequenceImplementation.CompleteSequencerBehaviorsTask() =>
            _sequencerBehaviorsTaskCompletionSource.TrySetResult(true);

19 Source : SequenceBase`1.cs
with MIT License
from BEagle1984

void ISequenceImplementation.NotifyProcessingCompleted()
        {
            _processingCompleteTaskCompletionSource.TrySetResult(true);
            _sequences?.OfType<ISequenceImplementation>()
                .ForEach(sequence => sequence.NotifyProcessingCompleted());
        }

19 Source : SequenceBase`1.cs
with MIT License
from BEagle1984

void ISequenceImplementation.NotifyProcessingFailed(Exception exception)
        {
            _processingCompleteTaskCompletionSource.TrySetException(exception);

            // Don't forward the error, it's enough to handle it once
            _sequences?.OfType<ISequenceImplementation>()
                .ForEach(sequence => sequence.NotifyProcessingCompleted());
            _sequencerBehaviorsTaskCompletionSource.TrySetResult(true);
        }

19 Source : ConsumeLoopHandler.cs
with MIT License
from BEagle1984

private async Task ConsumeAsync(
            TaskCompletionSource<bool> taskCompletionSource,
            CancellationToken cancellationToken)
        {
            _logger.LogConsumerLowLevelTrace(
                _consumer,
                "Starting consume loop... | instanceId: {instanceId}, taskId: {taskId}",
                () => new object[]
                {
                    Id,
                    taskCompletionSource.Task.Id
                });

            while (!cancellationToken.IsCancellationRequested)
            {
                if (!ConsumeOnce(cancellationToken))
                    break;
            }

            _logger.LogConsumerLowLevelTrace(
                _consumer,
                "Consume loop stopped. | instanceId: {instanceId}, taskId: {taskId}",
                () => new object[]
                {
                    Id,
                    taskCompletionSource.Task.Id
                });

            taskCompletionSource.TrySetResult(true);

            // There's unfortunately no async version of Confluent.Kafka.IConsumer.Consume() so we need to run
            // synchronously to stay within a single long-running thread with the Consume loop.
            // The call to DisconnectAsync is the only exception since we are exiting anyway and Consume will
            // not be called anymore.
            if (!cancellationToken.IsCancellationRequested)
                await _consumer.DisconnectAsync().ConfigureAwait(false);
        }

19 Source : ConsumerChannelsManager.cs
with MIT License
from BEagle1984

public Task StopReadingAsync(TopicParreplacedion topicParreplacedion)
        {
            int channelIndex = GetChannelIndex(topicParreplacedion);

            if (!_readCancellationTokenSource[channelIndex].IsCancellationRequested)
            {
                _logger.LogConsumerLowLevelTrace(
                    _consumer,
                    "Stopping channel {channelIndex} processing loop.",
                    () => new object[] { channelIndex });

                _readCancellationTokenSource[channelIndex].Cancel();
            }

            if (!IsReading[channelIndex])
                _readTaskCompletionSources[channelIndex].TrySetResult(true);

            return _readTaskCompletionSources[channelIndex].Task;
        }

19 Source : ConsumerChannelManager.cs
with MIT License
from BEagle1984

public void StopReading()
        {
            _readCancellationTokenSource.Cancel();
            _channel.Writer.TryComplete();

            if (!IsReading)
                _readTaskCompletionSource.TrySetResult(true);
        }

19 Source : ConsumerChannelManager.cs
with MIT License
from BEagle1984

[SuppressMessage("", "CA1031", Justification = Justifications.ExceptionLogged)]
        private async Task ReadChannelAsync()
        {
            try
            {
                _logger.LogConsumerLowLevelTrace(Consumer, "Starting channel processing loop...");

                while (!_readCancellationTokenSource.IsCancellationRequested)
                {
                    await ReadChannelOnceAsync().ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                // Ignore
                _logger.LogConsumerLowLevelTrace(
                    Consumer,
                    "Exiting channel processing loop (operation canceled).");
            }
            catch (Exception ex)
            {
                if (ex is not ConsumerPipelineFatalException)
                    _logger.LogConsumerFatalError(Consumer, ex);

                IsReading = false;
                _readTaskCompletionSource.TrySetResult(false);

                await _mqttClientWrapper.Consumer!.DisconnectAsync().ConfigureAwait(false);
            }

            IsReading = false;
            _readTaskCompletionSource.TrySetResult(true);

            _logger.LogConsumerLowLevelTrace(Consumer, "Exited channel processing loop.");
        }

19 Source : WSClient.cs
with Apache License 2.0
from beetlex-io

protected virtual void OnConnectResponse(Exception exception, Response response)
        {
            Response = response;
            Task.Run(() =>
            {
                if (exception != null)
                {
                    OnWSConnected = false;
                    mWScompletionSource?.TrySetException(exception);
                }
                else
                {
                    if (response.Code == 101)
                    {
                        OnWSConnected = true;
                        mWScompletionSource?.TrySetResult(true);

                    }
                    else
                    {
                        OnWSConnected = false;
                        mWScompletionSource?.TrySetException(new BXException($"ws connect error {response.Code} {response.Message}"));

                    }
                }
            });
        }

19 Source : WSClient.cs
with Apache License 2.0
from beetlex-io

protected virtual void OnConnectResponse(Exception exception, Response response)
        {
            Response = response;
            Task.Run(() =>
            {
                if (exception != null)
                {
                    OnWSConnected = false;
                    mWScompletionSource?.TrySetException(exception);
                }
                else
                {
                    if (response.Code != 101)
                    {
                        OnWSConnected = false;
                        mWScompletionSource?.TrySetException(new BXException($"ws connect error {response.Code} {response.Message}"));

                    }
                    else
                    {
                        OnWSConnected = true;
                        mWScompletionSource?.TrySetResult(true);
                    }
                }
            });
        }

19 Source : BaseNetworkProtocol.cs
with MIT License
from Beffyman

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 Source : BaseNetworkProtocol.cs
with MIT License
from Beffyman

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 Source : Extensions.cs
with MIT License
from BreezeHub

internal static Task ConnectAsync(this Socket socket, EndPoint endpoint, CancellationToken cancellationToken)
		{
			var args = new SocketAsyncEventArgs();
			CancellationTokenRegistration registration = default(CancellationTokenRegistration);

			TaskCompletionSource<bool> clientSocket = new TaskCompletionSource<bool>();
			Action processClientSocket = () =>
			{
				try
				{
					registration.Dispose();
				}
				catch { }
				if(cancellationToken.IsCancellationRequested)
					clientSocket.TrySetCanceled(cancellationToken);
				else if(args.SocketError != SocketError.Success)
					clientSocket.TrySetException(new SocketException((int)args.SocketError));
				else
					clientSocket.TrySetResult(true);
			};
			args.RemoteEndPoint = endpoint;
			args.Completed += (s, e) => processClientSocket();
			registration = cancellationToken.Register(() =>
			{
				clientSocket.TrySetCanceled(cancellationToken);
				try
				{
					registration.Dispose();
				}
				catch { }
			});
			cancellationToken.Register(() =>
			{
				clientSocket.TrySetCanceled(cancellationToken);
			});
			if(!socket.ConnectAsync(args))
				processClientSocket();
			return clientSocket.Task;
		}

19 Source : CustomThreadPool.cs
with MIT License
from BreezeHub

void RunLoop()
		{
			try
			{
				foreach(var act in _Actions.GetConsumingEnumerable(_Cancel.Token))
				{
					act.Item1();
				}
			}
			catch(OperationCanceledException) when(_Cancel.IsCancellationRequested) { }
			catch(Exception ex) { _Cancel.Cancel(); _UnhandledException = ex; }
			if(Interlocked.Increment(ref _ExitedCount) == _Threads.Length)
			{
				foreach(var action in _Actions)
				{
					try
					{
						action.Item2.TrySetCanceled();
					}
					catch { }
				}
				_Exited.TrySetResult(true);
			}
		}

19 Source : NBXplorerListener.cs
with MIT License
from btcpayserver

private async Task Listen(BTCPayWallet wallet)
        {
            var network = wallet.Network;
            bool cleanup = false;
            try
            {
                if (_SessionsByCryptoCode.ContainsKey(network.CryptoCode))
                    return;
                var client = _ExplorerClients.GetExplorerClient(network);
                if (client == null)
                    return;
                if (_Cts.IsCancellationRequested)
                    return;
                var session = await client.CreateWebsocketNotificationSessionAsync(_Cts.Token).ConfigureAwait(false);
                if (!_SessionsByCryptoCode.TryAdd(network.CryptoCode, session))
                {
                    await session.DisposeAsync();
                    return;
                }
                cleanup = true;

                using (session)
                {
                    await session.ListenNewBlockAsync(_Cts.Token).ConfigureAwait(false);
                    await session.ListenAllTrackedSourceAsync(cancellation: _Cts.Token).ConfigureAwait(false);

                    Logs.PayServer.LogInformation($"{network.CryptoCode}: Checking if any pending invoice got paid while offline...");
                    int paymentCount = await FindPaymentViaPolling(wallet, network);
                    Logs.PayServer.LogInformation($"{network.CryptoCode}: {paymentCount} payments happened while offline");

                    Logs.PayServer.LogInformation($"Connected to WebSocket of NBXplorer ({network.CryptoCode})");
                    while (!_Cts.IsCancellationRequested)
                    {
                        var newEvent = await session.NextEventAsync(_Cts.Token).ConfigureAwait(false);
                        switch (newEvent)
                        {
                            case NBXplorer.Models.NewBlockEvent evt:
                                await UpdatePaymentStates(wallet, await _InvoiceRepository.GetPendingInvoices());
                                _Aggregator.Publish(new Events.NewBlockEvent() { CryptoCode = evt.CryptoCode });
                                break;
                            case NBXplorer.Models.NewTransactionEvent evt:
                                if (evt.DerivationStrategy != null)
                                {
                                    wallet.InvalidateCache(evt.DerivationStrategy);
                                    var validOutputs = network.GetValidOutputs(evt).ToList();
                                    if (!validOutputs.Any())
                                        break;
                                    foreach (var output in validOutputs)
                                    {
                                        var key = output.Item1.ScriptPubKey.Hash + "#" +
                                                  network.CryptoCode.ToUpperInvariant();
                                        var invoice = (await _InvoiceRepository.GetInvoicesFromAddresses(new[] {key}))
                                            .FirstOrDefault();
                                        if (invoice != null)
                                        {
                                            var address = network.NBXplorerNetwork.CreateAddress(evt.DerivationStrategy,
                                                output.Item1.KeyPath, output.Item1.ScriptPubKey);

                                            var paymentData = new BitcoinLikePaymentData(address,
                                                output.matchedOutput.Value, output.outPoint,
                                                evt.TransactionData.Transaction.RBF, output.matchedOutput.KeyPath);

                                            var alreadyExist = invoice
                                                .GetAllBitcoinPaymentData(false).Any(c => c.GetPaymentId() == paymentData.GetPaymentId());
                                            if (!alreadyExist)
                                            {
                                                var payment = await _paymentService.AddPayment(invoice.Id,
                                                    DateTimeOffset.UtcNow, paymentData, network);
                                                if (payment != null)
                                                    await ReceivedPayment(wallet, invoice, payment,
                                                        evt.DerivationStrategy);
                                            }
                                            else
                                            {
                                                await UpdatePaymentStates(wallet, invoice.Id);
                                            }
                                        }

                                    }
                                }

                                _Aggregator.Publish(new NewOnChainTransactionEvent()
                                {
                                    CryptoCode = wallet.Network.CryptoCode,
                                    NewTransactionEvent = evt
                                });

                                break;
                            default:
                                Logs.PayServer.LogWarning("Received unknown message from NBXplorer");
                                break;
                        }
                    }
                }
            }
            catch when (_Cts.IsCancellationRequested) { }
            catch (Exception ex)
            {
                Logs.PayServer.LogError(ex, $"Error while connecting to WebSocket of NBXplorer ({network.CryptoCode})");
            }
            finally
            {
                if (cleanup)
                {
                    Logs.PayServer.LogInformation($"Disconnected from WebSocket of NBXplorer ({network.CryptoCode})");
                    _SessionsByCryptoCode.TryRemove(network.CryptoCode, out WebsocketNotificationSession unused);
                    if (_SessionsByCryptoCode.IsEmpty && _Cts.IsCancellationRequested)
                    {
                        _RunningTask.TrySetResult(true);
                    }
                }
            }
        }

19 Source : SSHClientExtensions.cs
with MIT License
from btcpayserver

public static async Task DisconnectAsync(this SshClient sshClient, CancellationToken cancellationToken = default)
        {
            if (sshClient == null)
                throw new ArgumentNullException(nameof(sshClient));

            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            new Thread(() =>
            {
                try
                {
                    sshClient.Disconnect();
                    tcs.TrySetResult(true);
                }
                catch
                {
                    tcs.TrySetResult(true); // We don't care about exception
                }
            })
            { IsBackground = true }.Start();
            using (cancellationToken.Register(() => tcs.TrySetCanceled()))
            {
                await tcs.Task;
            }
        }

19 Source : CustomThreadPool.cs
with MIT License
from btcpayserver

void RunLoop()
        {
            try
            {
                foreach (var act in _Actions.GetConsumingEnumerable(_Cancel.Token))
                {
                    act.Item1();
                }
            }
            catch (OperationCanceledException) when (_Cancel.IsCancellationRequested) { }
            catch (Exception ex)
            {
                _Cancel.Cancel();
                _UnhandledException = ex;
            }
            if (Interlocked.Increment(ref _ExitedCount) == _Threads.Length)
            {
                foreach (var action in _Actions)
                {
                    try
                    {
                        action.Item2.TrySetCanceled();
                    }
                    catch { }
                }
                _Exited.TrySetResult(true);
            }
        }

19 Source : PullPaymentHostedService.cs
with MIT License
from btcpayserver

private async Task HandleCancel(CancelRequest cancel)
        {
            try
            {
                using var ctx = this._dbContextFactory.CreateContext();
                List<PayoutData> payouts = null;
                if (cancel.PullPaymentId != null)
                {
                    ctx.PullPayments.Attach(new Data.PullPaymentData() { Id = cancel.PullPaymentId, Archived = true })
                        .Property(o => o.Archived).IsModified = true;
                    payouts = await ctx.Payouts
                            .Where(p => p.PullPaymentDataId == cancel.PullPaymentId)
                            .ToListAsync();
                }
                else
                {
                    var payoutIds = cancel.PayoutIds.ToHashSet();
                    payouts = await ctx.Payouts
                            .Where(p => payoutIds.Contains(p.Id))
                            .ToListAsync();
                }

                foreach (var payout in payouts)
                {
                    if (payout.State != PayoutState.Completed && payout.State != PayoutState.InProgress)
                        payout.State = PayoutState.Cancelled;
                }
                await ctx.SaveChangesAsync();
                cancel.Completion.TrySetResult(true);
            }
            catch (Exception ex)
            {
                cancel.Completion.TrySetException(ex);
            }
        }

19 Source : MainWindowViewModel.cs
with MIT License
from btcpayserver

internal void Authorize(string origin, TaskCompletionSource<bool> tcs)
        {
            if (AuthorizedOrigins.Contains(origin))
            {
                tcs.TrySetResult(true);
                return;
            }
            if (taskCompletionSource != null)
            {
                if (Origin != origin)
                    taskCompletionSource.TrySetResult(false);
                else
                    taskCompletionSource.Task.ContinueWith(result => taskCompletionSource.TrySetResult(result.Result));
                return;
            }
            else
            {
                IsVisible = true;
                Origin = origin;
                taskCompletionSource = tcs;
            }
        }

19 Source : MockDelay.cs
with MIT License
from btcpayserver

public async Task Advance(TimeSpan time)
        {
            _Now += time;
            List<WaitObj> overdue = new List<WaitObj>();
            lock (waits)
            {
                foreach (var wait in waits.ToArray())
                {
                    if (_Now >= wait.Expiration)
                    {
                        overdue.Add(wait);
                        waits.Remove(wait);
                    }
                }
            }
            foreach (var o in overdue)
                o.CTS.TrySetResult(true);
            try
            {
                await Task.WhenAll(overdue.Select(o => o.CTS.Task).ToArray());
            }
            catch { }
        }

19 Source : AsyncActionBatcher.cs
with Apache License 2.0
from busterwood

async void TimerCallback(object state)
#pragma warning restore RECS0165 // Asynchronous methods should return a Task instead of void
        {
            // capture the inputs and completion source at this point in time
            TaskCompletionSource<bool> tcs;
            List<T> inputs;
            lock (_gate)
            {
                _timer.Change(Timeout.Never, Timeout.Never);  // reset the timer, the DoAsync method will start it again if needed
                tcs = _completionSource;
                inputs = _inputs;
                _completionSource = null;
                _inputs = null;
            }

            // do the action on many inputs in one go
            try
            {
                await _doMany(inputs);
            }
            catch (Exception ex)
            {
                // it failed, preplaced the exception to all waiters
                tcs.TrySetException(ex);
                return;
            }

            // tell the waiters that the task has now been done
            tcs.TrySetResult(true);
        }

19 Source : Sender.cs
with Apache License 2.0
from busterwood

public new void SetResult(bool result)
        {
#if NET452
            System.Threading.Tasks.Task.Run(() => { base.TrySetResult(result); });
#else
            base.TrySetResult(result);
#endif
        }

19 Source : SocketEx.cs
with Apache License 2.0
from caozhiyuan

public static Task ConnectExAsync(this Socket socket, EndPoint remoteEp)
        {
            var tcs = new TaskCompletionSource<bool>(socket);
            socket.BeginConnect(remoteEp, iar =>
            {
                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
                try
                {
                    ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
                    innerTcs.TrySetResult(true);
                }
                catch (Exception e)
                {
                    innerTcs.TrySetException(e);
                }
            }, tcs);
            return tcs.Task;
        }

19 Source : FixedChannelPool.cs
with Apache License 2.0
from cdy816

async void Release0(object channel, object promise)
        {
            var tsc = promise as TaskCompletionSource<bool>;
            try
            {
                var result = await this.DoReleaseAsync((IChannel)channel);
                tsc.TrySetResult(result);
            }
            catch (Exception ex)
            {
                tsc.TrySetException(ex);
            }
        }

19 Source : SimpleChannelPool.cs
with Apache License 2.0
from cdy816

async void DoReleaseChannel(object channel, object state)
        {
            var promise = state as TaskCompletionSource<bool>;
            try
            {
                var result = await this.DoReleaseChannel((IChannel)channel);
                promise.TrySetResult(result);
            }
            catch (Exception ex)
            {
                promise.TrySetException(ex);
            }
        }

19 Source : CefRequestContext.cs
with MIT License
from CefNet

private unsafe void SetPreferenceInternal(string name, CefValue value, TaskCompletionSource<bool> taskCompletion)
		{
			int retval;
			string errorMsg;
			fixed (char* s0 = name)
			{
				cef_string_t error;
				cef_string_t cstr0 = new cef_string_t { Str = s0, Length = name.Length };
				retval = NativeInstance->SetPreference(&cstr0, value is null ? null : value.GetNativeInstance(), &error);
				GC.KeepAlive(this);
				errorMsg = CefString.ReadAndFree(&error);
			}
			if (retval != 0)
			{
				taskCompletion?.TrySetResult(true);
				return;
			}
			Exception exception = errorMsg is null ? new InvalidOperationException() : new InvalidOperationException(errorMsg);
			if (taskCompletion is null)
				throw exception;
			taskCompletion.TrySetException(exception);
		}

19 Source : CefNetApplication.cs
with MIT License
from CefNet

public async void SignalForShutdown(Action callback)
		{
			var shutdownTaskSource = new TaskCompletionSource<bool>();
			shutdownTaskSource = Interlocked.CompareExchange(ref _shutdownSignalTaskSource, shutdownTaskSource, null) ?? shutdownTaskSource;
			if (Volatile.Read(ref _browsersCount) == 0)
				shutdownTaskSource.TrySetResult(false);
			await shutdownTaskSource.Task.ConfigureAwait(false);
			GC.Collect();
			GC.WaitForPendingFinalizers();
			callback();
		}

19 Source : CefNetApplication.cs
with MIT License
from CefNet

protected internal virtual void OnBrowserDestroyed(CefBrowser browser)
		{
			if (Interlocked.Decrement(ref _browsersCount) == 0)
				Volatile.Read(ref _shutdownSignalTaskSource)?.TrySetResult(true);
		}

19 Source : AvaloniaContextMenuRunner.cs
with MIT License
from CefNet

public void RunMenuAt(Control control, Point point)
		{
			_completionSource = new TaskCompletionSource<bool>();
			Dispatcher.UIThread.Post(() =>
			{
				try
				{
					Menu.PlacementMode = PlacementMode.Pointer;
					Menu.PlacementRect = new Rect(point.X, point.Y, 1, 1);
					Menu.Open(control);
				}
				finally
				{
					_completionSource.TrySetResult(true);
				}
			});
		}

19 Source : AvaloniaContextMenuRunner.cs
with MIT License
from CefNet

public void Cancel()
		{
			_completionSource?.TrySetResult(false);
			Callback?.Cancel();
			Callback = null;
		}

19 Source : TaskExtensions.cs
with GNU General Public License v3.0
from chaincase-app

public static async Task<T> WithAwaitCancellationAsync<T>(this Task<T> me, CancellationToken cancel, int waitForGracefulTerminationMilliseconds = 0)
		{
			// The task completion source.
			var tcs = new TaskCompletionSource<bool>();

			// Register with the cancellation token.
			using (cancel.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
			{
				// If the task waited on is the cancellation token...
				if (me != await Task.WhenAny(me, tcs.Task).ConfigureAwait(false))
				{
					if (waitForGracefulTerminationMilliseconds <= 0)
					{
						throw new OperationCanceledException(cancel);
					}
					else
					{
						using var cts = new CancellationTokenSource(waitForGracefulTerminationMilliseconds);
						return await me.WithAwaitCancellationAsync(cts.Token).ConfigureAwait(false);
					}
				}
			}

			// Wait for one or the other to complete.
			return await me.ConfigureAwait(false);
		}

19 Source : TaskExtensions.cs
with GNU General Public License v3.0
from chaincase-app

public static async Task WithAwaitCancellationAsync(this Task me, CancellationToken cancel, int waitForGracefulTerminationMilliseconds = 0)
		{
			// The task completion source.
			var tcs = new TaskCompletionSource<bool>();

			// Register with the cancellation token.
			using (cancel.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
			{
				// If the task waited on is the cancellation token...
				if (me != await Task.WhenAny(me, tcs.Task).ConfigureAwait(false))
				{
					if (waitForGracefulTerminationMilliseconds <= 0)
					{
						throw new OperationCanceledException(cancel);
					}
					else
					{
						using var cts = new CancellationTokenSource(waitForGracefulTerminationMilliseconds);
						await me.WithAwaitCancellationAsync(cts.Token).ConfigureAwait(false);
						return;
					}
				}
			}

			// Wait for one or the other to complete.
			await me.ConfigureAwait(false);
		}

19 Source : JsonRpcServer.cs
with GNU General Public License v3.0
from chaincase-app

private async Task<HttpListenerContext> GetHttpContextAsync(CancellationToken cancellationToken)
		{
			var getHttpContextTask = Listener.GetContextAsync();
			var tcs = new TaskCompletionSource<bool>();
			using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs))
			{
				var firstTaskToComplete = await Task.WhenAny(getHttpContextTask, tcs.Task).ConfigureAwait(false);
				if (getHttpContextTask != firstTaskToComplete)
				{
					cancellationToken.ThrowIfCancellationRequested();
				}
			}
			return await getHttpContextTask.ConfigureAwait(false);
		}

19 Source : AudioExtrasSource.cs
with MIT License
from chatop2020

public Task SendAudioFromStream(Stream audioStream, AudioSamplingRatesEnum streamSampleRate)
        {
            if (!_isClosed && audioStream != null && audioStream.Length > 0)
            {
                // Stop any existing send from stream operation.
                StopSendFromAudioStream();

                TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

                Action handler = null;
                handler = () =>
                {
                    tcs.TrySetResult(true);
                    OnSendFromAudioStreamComplete -= handler;
                };
                OnSendFromAudioStreamComplete += handler;

                InitialiseSendAudioFromStreamTimer(audioStream, streamSampleRate);

                _streamSourceTimer.Change(_audioSamplePeriodMilliseconds, _audioSamplePeriodMilliseconds);

                return tcs.Task;
            }
            else
            {
                return Task.CompletedTask;
            }
        }

19 Source : SocketService.cs
with MIT License
from CheshireCaat

private async Task ConnectAsync()
        {
            var tcs = new TaskCompletionSource<bool>();

            _socket.OnClose += (sender, args) =>
            {
                if (!args.WasClean)
                {
                    if (_attempts == 60)
                    {
                        tcs.TrySetException(new SocketNotConnectedException());
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    _socket.Connect();
                    _attempts++;
                }

                OnClose?.Invoke();
            };

            _socket.OnOpen += (sender, args) =>
            {
                tcs.TrySetResult(true);
                OnOpen?.Invoke();
            };

            _socket.ConnectAsync();

            await tcs.Task.ConfigureAwait(false);
        }

19 Source : TaskExtensions.cs
with MIT License
from christiandelbianco

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 task.Result;
        }

19 Source : AnimationComponent.cs
with Apache License 2.0
from codaris

private void Events_RobotState(object sender, Events.RobotStateEventArgs e)
        {
            // If we aren't waiting for a result, return
            if (animationRunningResult == null) return;

            // If we aren't animating and 250 milliseconds has past then set the result.
            var diff = DateTime.Now.Subtract(lastAnimationStart).TotalMilliseconds;
            if (!e.Status.IsAnimating && diff > 250)
            {
                animationRunningResult.TrySetResult(true);
                animationRunningResult = null;
                OnPropertyChanged(nameof(IsAnimating));
            }
        }

19 Source : AnimationComponent.cs
with Apache License 2.0
from codaris

private void StartAnimationTracking()
        {
            if (animationRunningResult != null) animationRunningResult.TrySetResult(true);
            lastAnimationStart = DateTime.Now;
            animationRunningResult = new TaskCompletionSource<bool>();
            OnPropertyChanged(nameof(IsAnimating));
        }

19 Source : ControlComponent.cs
with Apache License 2.0
from codaris

private void ProcessControlResponse(BehaviorControlResponse response)
        {
            var type = response.ResponseTypeCase;
            switch (type)
            {
                case BehaviorControlResponse.ResponseTypeOneofCase.ControlGrantedResponse:
                case BehaviorControlResponse.ResponseTypeOneofCase.ControlLostEvent:
                    HasControl = type == BehaviorControlResponse.ResponseTypeOneofCase.ControlGrantedResponse;
                    behaviorResult?.TrySetResult(HasControl);
                    if (type == BehaviorControlResponse.ResponseTypeOneofCase.ControlGrantedResponse) ControlGranted?.Invoke(this, new ControlGrantedEventArgs());
                    if (type == BehaviorControlResponse.ResponseTypeOneofCase.ControlLostEvent) ControlLost?.Invoke(this, new ControlLostEventArgs());
                    break;
                case BehaviorControlResponse.ResponseTypeOneofCase.ReservedControlLostEvent:
                    HasControl = false;
                    behaviorResult?.TrySetResult(false);
                    ControlLost?.Invoke(this, new ControlLostEventArgs());
                    break;
            }
        }

19 Source : AsyncDuplexEventLoop.cs
with Apache License 2.0
from codaris

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Calls exception handler action.")]
        public async Task StartAsync()
        {
            if (cancellationTokenSource != null)
            {
                throw new InvalidOperationException("The event loop has already been started.");
            }

            try
            {
                // Reset the termination exception
                Exception = null;

                // Create the cancellation token source
                cancellationTokenSource = new CancellationTokenSource();
                endTaskCompletionSource = new TaskCompletionSource<bool>();
                var token = cancellationTokenSource.Token;
                using (feed = startFunction(token))
                {
                    // Trigger the start completion source
                    startTaskCompletionSource?.TrySetResult(true);
                    // While the feed has not been cancelled
                    while (!token.IsCancellationRequested)
                    {
                        // Get a single result from the stream
                        var result = await feed.ResponseStream.MoveNext(token).ConfigureAwait(false);
                        if (!result) break;
                        resultAction(feed.ResponseStream.Current);
                    }
                }
            }
            catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
            {
                // Ignore cancellation exceptions
            }
            catch (Exception ex)
            {
                // All event loop exception are caught because exceptions don't propagate well on the background thread.
                // Instead, the exception is logged here.
                Exception = ex;
                exceptionHandler?.Invoke(ex);
                endTaskCompletionSource.TrySetException(ex);
            }
            finally
            {
                feed?.Dispose();
                feed = null;
                cancellationTokenSource?.Dispose();
                cancellationTokenSource = null;
                endTaskCompletionSource?.TrySetResult(true);
                endTaskCompletionSource = null;
                endAction?.Invoke();
            }
        }

19 Source : AsyncEventLoop.cs
with Apache License 2.0
from codaris

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Calls exception handler action.")]
        public async Task StartAsync()
        {
            if (cancellationTokenSource != null)
            {
                throw new InvalidOperationException("The event loop has already been started.");
            }

            try
            {
                // Reset the exception
                Exception = null;

                // Create the cancellation token source
                cancellationTokenSource = new CancellationTokenSource();
                endTaskCompletionSource = new TaskCompletionSource<bool>();
                var token = cancellationTokenSource.Token;

                using (var feed = startFunction(token))
                {
                    // Trigger the start completion source
                    startTaskCompletionSource?.TrySetResult(true);
                    // While the feed has not been cancelled retrieve images
                    while (!token.IsCancellationRequested)
                    {
                        // Get a single result from the stream
                        var result = await feed.ResponseStream.MoveNext(token).ConfigureAwait(false);
                        if (!result) break;
                        var response = feed.ResponseStream.Current;
                        resultAction(response);
                    }
                }
            }
            catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
            {
                // Ignore cancellation exceptions
            }
            catch (Exception ex)
            {
                // All event loop exception are caught because exceptions don't propagate well on the background thread.
                // Instead, the exception is logged here.
                Exception = ex;
                exceptionHandler?.Invoke(ex);
                endTaskCompletionSource.TrySetException(ex);
            }
            finally
            {
                cancellationTokenSource.Dispose();
                cancellationTokenSource = null;
                endTaskCompletionSource.TrySetResult(true);
                endTaskCompletionSource = null;
                endAction?.Invoke();
            }
        }

19 Source : SnowballConsensusTests.cs
with MIT License
from comrade-coop

[Theory]
        [InlineData(5)]
#if SLOWTESTS
        [InlineData(100)]
        // [InlineData(2000)] // ~1m
#endif
        public async void Snowball_ConfirmsAndExecutes_SingleMessage(int peersCount)
        {
            var hashResolver = new FakeHashResolver();
            var executor = await ExecutorFakes.GetExecutor(ExecutorFakes.TestAgents);
            var peerConnectorProvider = new FakePeerConnectorProvider();
            var peers = Enumerable.Range(0, peersCount).Select(x => FakePeerConnectorProvider.GetFakePeer()).ToArray();

            var snowballParameters = await hashResolver.StoreAsync<object>(new SnowballParameters(5, 0.8, 25));
            var (chain, inputMessages, expectedOutputMessages) = await ExecutorFakes.GetTestAgentScenario(hashResolver, "Apocryph-SnowballConsensus", snowballParameters, peersCount);

            var chainId = Hash.From(chain);

            var started = new TaskCompletionSource<bool>();
            async IAsyncEnumerable<(Hash<Chain>, Slot?[])> kothStates()
            {
                await started.Task;
                yield return (chainId, peers.Select(peer => (Slot?)new Slot(peer, new byte[0])).ToArray());
            }

            var outputStreams = await SnowballFakes.StartSnowballNetwork(peers, hashResolver, peerConnectorProvider, chain, executor,
                peer => (inputMessages.ToAsyncEnumerable(), "-", kothStates()));

            started.TrySetResult(true);

            // NOTE: Using WhenAll here, since (A) we need to iterate all streams fully and (B) PerperFakeStream does not propagate completion

            var cancellation = new CancellationTokenSource();

            await Task.WhenAll(outputStreams.Select(async stream =>
            {
                try
                {
                    var enumerator = stream.GetAsyncEnumerator();
                    foreach (var expectedMessage in expectedOutputMessages)
                    {
                        await enumerator.MoveNextAsync(cancellation.Token);
                        replacedert.Equal(enumerator.Current, expectedMessage, SerializedComparer.Instance);
                    }
                    // NOTE: Would be nice to confirm there are no other stream items
                }
                catch (Exception e)
                {
                    _output.WriteLine(e.ToString());
                    throw;
                }
            }));

            cancellation.Cancel();
        }

19 Source : LifetimeManager.cs
with MIT License
from CoreWCF

public void Dispose()
        {
            lock (ThisLock)
            {
                if (_closed)
                {
                    return;
                }

                _closed = true;
                _tcs?.TrySetResult(false);
            }
        }

See More Examples