System.Threading.CancellationToken.Register(System.Action)

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

563 Examples 7

19 Source : SharedFuture.cs
with Apache License 2.0
from asynkron

public async Task<object> GetTask(CancellationToken cancellationToken)
            {
                try
                {
                    if (cancellationToken == default)
                    {
                        return await _tcs.Task;
                    }
                    
                    await using (cancellationToken.Register(() => _tcs.TrySetCanceled()))
                    {
                        return await _tcs.Task;
                    }
                }
                catch
                {
                    _parent.Cancel(Pid.RequestId);
                    _parent._onTimeout?.Invoke();
                    throw new TimeoutException("Request didn't receive any Response within the expected time.");
                }
            }

19 Source : ReceiveTimeoutTests.cs
with Apache License 2.0
from asynkron

private TaskCompletionSource<int> GetExpiringTaskCompletionSource(int timeoutMs = 60000)
        {
            var tcs = new TaskCompletionSource<int>();
            var ct = new CancellationTokenSource();
            ct.Token.Register(() => tcs.TrySetCanceled());
            ct.CancelAfter(timeoutMs);
            return tcs;
        }

19 Source : TestHelper.cs
with MIT License
from AzureAD

public static Task WaitForExitAsync(this Process process,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var tcs = new TaskCompletionSource<object>();
            process.EnableRaisingEvents = true;
            process.Exited += (sender, args) =>
            {
                Trace.WriteLine($"Process finished {process.Id}");
                tcs.TrySetResult(null);
            };

            if (cancellationToken != default(CancellationToken))
            {
                cancellationToken.Register(tcs.SetCanceled);
            }

            return tcs.Task;
        }

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

public async Task<int> ExcuteAsync(
            string workingDir,
            string fileName,
            string args,
            ConcurrentQueue<string> inputs = null,
            bool killProcessOnCancel = true,
            CancellationToken cancellationToken = default)
        {
            InitProcess(workingDir, fileName, args, killProcessOnCancel);

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            Interlocked.Increment(ref _streamReadCount);
            Interlocked.Increment(ref _streamReadCount);

            _stopWatch = Stopwatch.StartNew();

            _proc.Start();

            var readErrorTask = ReadStream(_proc.StandardError, _errorData);

            var readOutputTask = ReadStream(_proc.StandardOutput, _outputData);

            if (inputs != null)
            {
                var task = WriteStream(inputs, _proc.StandardInput, true);
            }
            else
            {
                // Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
                _proc.StandardInput.Close();
            }

            using (var registration = cancellationToken.Register(async () => await CancelAndKillProcessTree(killProcessOnCancel)))
            {
                _trace?.Verbose($"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;
                    }
                }

                ProcessOutput();

                _trace?.Info($"\nFinished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
            }

            return _proc.ExitCode;
        }

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

public async Task<int> ExcuteAsync(CancellationToken cancellationToken = default)
        {
            InitProcess(_workingDir, _fileName, _args, true);

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            Interlocked.Increment(ref _streamReadCount);
            Interlocked.Increment(ref _streamReadCount);

            _stopWatch = Stopwatch.StartNew();

            _proc.Start();

            var readErrorTask = ReadStream(_proc.StandardError, _errorData);

            var readOutputTask = ReadStream(_proc.StandardOutput, _outputData);

            if (_isInterActive)
            {
                var writeTask = WriteStream(_proc.StandardInput);
            }
            else
            {
                _proc.StandardInput.Close();
            }


            using (var registration = cancellationToken.Register(async () => await CancelAndKillProcessTree(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;
                    }
                }

                ProcessOutput();

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

            return _proc.ExitCode;
        }

19 Source : LottieComposition.cs
with Apache License 2.0
from Baseflow

public static Task<LottieComposition> FromJsonStringAsync(string jsonString, CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                    return Task.FromCanceled<LottieComposition>(cancellationToken);

                var tcs = new TaskCompletionSource<LottieComposition>();
                var cancelable = Factory.FromJsonString(jsonString, (composition) =>
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    tcs.SetResult(composition);
                });

                cancellationToken.Register(() =>
                {
                    if (!tcs.Task.IsCompleted)
                    {
                        cancelable.Cancel();
                        tcs.TrySetCanceled(cancellationToken);
                    }
                });

                return tcs.Task;
            }

19 Source : LottieComposition.cs
with Apache License 2.0
from Baseflow

public static Task<LottieComposition> FromInputStreamAsync(System.IO.Stream stream, CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                    return Task.FromCanceled<LottieComposition>(cancellationToken);

                var tcs = new TaskCompletionSource<LottieComposition>();
                var cancelable = Factory.FromInputStream(stream, (composition) =>
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    tcs.SetResult(composition);
                });

                cancellationToken.Register(() =>
                {
                    if (!tcs.Task.IsCompleted)
                    {
                        cancelable.Cancel();
                        tcs.TrySetCanceled(cancellationToken);
                    }
                });

                return tcs.Task;
            }

19 Source : LottieComposition.cs
with Apache License 2.0
from Baseflow

public static Task<LottieComposition> FromreplacedetFileNameAsync(Context context, string fileName, CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                    return Task.FromCanceled<LottieComposition>(cancellationToken);

                var tcs = new TaskCompletionSource<LottieComposition>();
                var cancelable = Factory.FromreplacedetFileName(context, fileName, (composition) =>
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    tcs.SetResult(composition);
                });

                cancellationToken.Register(() =>
                {
                    if (!tcs.Task.IsCompleted)
                    {
                        cancelable.Cancel();
                        tcs.TrySetCanceled(cancellationToken);
                    }
                });

                return tcs.Task;
            }

19 Source : BannerListener.cs
with Apache License 2.0
from bcgov

[System.Diagnostics.Codereplacedysis.SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Abstract clreplaced property")]
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            this.logger.LogInformation("DBChangeListener is starting");
            stoppingToken.Register(() =>
                this.logger.LogInformation($"DBChangeListener Shutdown as cancellation requested    "));
            int attempts = 0;
            while (!stoppingToken.IsCancellationRequested)
            {
                attempts++;
                this.logger.LogInformation($"Registering Channel Notification on channel {Channel}, attempts = {attempts}");
                try
                {
                    using var scope = this.services.CreateScope();
                    using GatewayDbContext dbContext = scope.ServiceProvider.GetRequiredService<GatewayDbContext>();
                    this.CommunicationService = scope.ServiceProvider.GetRequiredService<ICommunicationService>();
                    using NpgsqlConnection con = (NpgsqlConnection)dbContext.Database.GetDbConnection();
                    await con.OpenAsync(stoppingToken).ConfigureAwait(true);
                    con.Notification += this.ReceiveEvent;
                    using NpgsqlCommand cmd = new NpgsqlCommand();
                    cmd.CommandText = @$"LISTEN ""{Channel}"";";
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    await cmd.ExecuteNonQueryAsync(stoppingToken).ConfigureAwait(true);

                    while (!stoppingToken.IsCancellationRequested)
                    {
                        // Wait for the event
                        await con.WaitAsync(stoppingToken).ConfigureAwait(true);
                    }

                    await con.CloseAsync().ConfigureAwait(true);
                }
                catch (NpgsqlException e)
                {
                    this.logger.LogError($"DB Error encountered in WaitChannelNotification: {Channel}\n{e.ToString()}");
                    if (!stoppingToken.IsCancellationRequested)
                    {
                        await Task.Delay(SleepDuration, stoppingToken).ConfigureAwait(true);
                    }
                }

                this.logger.LogWarning($"DBChangeListener on {Channel} exiting...");
            }
        }

19 Source : BaseNetworkProtocol.cs
with MIT License
from Beffyman

public static IDisposable CreateTimeoutScope(this IDisposable disposable, TimeSpan timeSpan)
		{
			var cancellationTokenSource = new CancellationTokenSource(timeSpan);
			var cancellationTokenRegistration = cancellationTokenSource.Token.Register(disposable.Dispose);
			return new DisposableScope(
			  () =>
			  {
				  cancellationTokenRegistration.Dispose();
				  cancellationTokenSource.Cancel();
				  cancellationTokenSource.Dispose();
				  disposable.Dispose();
			  });
		}

19 Source : FiguraAuthServer.cs
with GNU Lesser General Public License v2.1
from Blancworks

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            int port = 25565;

            serverListener = new TcpListener(IPAddress.Any, port);
            serverListener.Start();
            Logger.LogMessage("Started 'Minecraft' server on port " + port);

            try
            {
                using (stoppingToken.Register(serverListener.Stop))
                    while (!stoppingToken.IsCancellationRequested)
                    {
                        await GetNextConnection();
                    }
            }
            finally
            {
                serverListener.Stop();
            }
        }

19 Source : SocketListener.cs
with MIT License
from blish-hud

public void Start(IPEndPoint localEndPoint) {
            if (_cancellationTokenSource is { IsCancellationRequested: false }) {
                Logger.Warn("Start() was called more than once. Call Stop() before calling Start() again.");
                return;
            }

            _cancellationTokenSource = new CancellationTokenSource();

            var listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) {
                ReceiveBufferSize = _bufferSize
            };

            _cancellationTokenSource.Token.Register(() => Release(listenSocket));

            var socketEventArgs = new SocketAsyncEventArgs();
            socketEventArgs.Completed += OnIoCompleted;
            socketEventArgs.SetBuffer(new byte[_bufferSize], 0, _bufferSize);
            socketEventArgs.AcceptSocket   = listenSocket;
            socketEventArgs.RemoteEndPoint = localEndPoint;

            try {
                // The next line returns true when the operation is pending; false when it completed without delay
                if (!listenSocket.ConnectAsync(socketEventArgs)) {
                    ProcessConnect(socketEventArgs);
                }
            } catch (Exception e) {
                Logger.Warn(e, "Failed to connect to Arcdps-BHUD bridge.");
            }
        }

19 Source : PerformanceCounterManager.cs
with GNU General Public License v3.0
from bonarr

public void Initialize(string instanceName, CancellationToken hostShutdownToken)
        {
            if (_initialized)
            {
                return;
            }

            var needToRegisterWithShutdownToken = false;
            lock (_initLocker)
            {
                if (!_initialized)
                {
                    instanceName = instanceName ?? Guid.NewGuid().ToString();
                    SetCounterProperties(instanceName);
                    // The initializer ran, so let's register the shutdown cleanup
                    if (hostShutdownToken != CancellationToken.None)
                    {
                        needToRegisterWithShutdownToken = true;
                    }
                    _initialized = true;
                }
            }

            if (needToRegisterWithShutdownToken)
            {
                hostShutdownToken.Register(UnloadCounters);
            }
        }

19 Source : StreamSink.cs
with MIT License
from bonsai-rx

static Stream CreateStream(string path, bool overwrite, CancellationToken cancellationToken)
        {
            const int MaxNumberOfServerInstances = 1;
            if (path.StartsWith(PipeServerPrefix))
            {
                var pipeName = path.Split(new[] { PipeServerPrefix }, StringSplitOptions.RemoveEmptyEntries).Single();
                var stream = new NamedPipeServerStream(
                    pipeName,
                    PipeDirection.Out,
                    MaxNumberOfServerInstances,
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous);
                try
                {
                    using (var cancellation = cancellationToken.Register(stream.Close))
                    {
                        stream.WaitForConnection();
                    }
                }
                catch { stream.Close(); throw; }
                return stream;
            }
            else return new FileStream(path, overwrite ? FileMode.Create : FileMode.CreateNew);
        }

19 Source : MemberCommunicator.cs
with GNU General Public License v3.0
from bosima

public void Download(Member member, string msgType, Dictionary<string, string> paras, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();

            var paraStr = string.Empty;
            if (paras != null && paras.Count > 0)
            {
                foreach (var paraKey in paras.Keys)
                {
                    paraStr += string.Format("&{0}={1}", paraKey, HttpUtility.UrlEncode(paras[paraKey], Encoding.UTF8));
                }
            }

            string url = string.Format("{0}{1}{2}", member.CommunicationAddress, msgType,
                (!string.IsNullOrWhiteSpace(paraStr) ? "?" + paraStr.TrimStart('&') : string.Empty));

            LogWriter.Write("通信路径:" + url);

            int tryTimes = 2;
            while (tryTimes > 0)
            {
                try
                {
                    WebClient client = new WebClient();
                    var downloadTask = client.DownloadDataTaskAsync(new Uri(url));
                    byte[] result;

                    using (cancellationToken.Register(client.CancelAsync))
                    {
                        result = downloadTask.Result;
                    }

                    // 也许注释掉的方法更好
                    //while (!downloadTask.Wait(TimeSpan.FromSeconds(0.2)))
                    //{
                    //    cancellationToken.ThrowIfCancellationRequested();
                    //}
                    //result = downloadTask.Result;

                    OnReceiveWebResponseHandler?.Invoke(msgType, paras, result, cancellationToken);
                    break;
                }
                catch (Exception ex)
                {
                    tryTimes--;
                    if (tryTimes <= 0)
                    {
                        LogWriter.Write("下载文件处理异常", ex);
                        throw;
                    }

                    LogWriter.Write("下载文件处理异常", ex, LogLevel.Warn);

                }
            }
        }

19 Source : SwiftProcess.cs
with GNU General Public License v3.0
from bosima

public void ExecuteTask(CancellationToken cancellationToken = default(CancellationToken))
        {
            // 当前作业执行命令
            var fileName = _job.FileName;
            var paras = string.Format(" -p -t {0} -jr {1} -jn {2} -jp {3}", _jobTask.Id, _job.Id, _job.Name, _job.CurrentJobSpacePath);

            var commandParas = FormatProcessCommandParas(fileName, paras);
            LogWriter.Write(string.Format("已格式化命令行参数"), Log.LogLevel.Trace);
            fileName = commandParas.Item1;
            paras = commandParas.Item2;

            var commandLine = string.Format("{0}:{1}:{2}", _job.CurrentJobProgramPath, fileName, paras);

            LogWriter.Write(string.Format("SwiftProcess->ExecuteTask Command: {0}", commandLine), Log.LogLevel.Debug);

            using (var ctsTokenRegistion = cancellationToken.Register(Kill))
            {
                Execute("ExecuteTask", _job.CurrentJobProgramPath, fileName, paras);
            }
        }

19 Source : SwiftProcess.cs
with GNU General Public License v3.0
from bosima

public void CollectTaskResult(CancellationToken cancellationToken = default(CancellationToken))
        {
            // 当前作业执行命令
            var fileName = _job.FileName;
            var paras = string.Format(" -m -jr {0} -jn {1} -jp {2}", _job.Id, _job.Name, _job.CurrentJobSpacePath);

            var commandParas = FormatProcessCommandParas(fileName, paras);
            LogWriter.Write(string.Format("已格式化命令行参数"), Log.LogLevel.Trace);
            fileName = commandParas.Item1;
            paras = commandParas.Item2;

            var commandLine = string.Format("{0}:{1}:{2}", _job.CurrentJobProgramPath, fileName, paras);

            LogWriter.Write(string.Format("SwiftProcess->CollectTaskResult Command: {0}", commandLine), Log.LogLevel.Debug);

            using (var ctsTokenRegistion = cancellationToken.Register(Kill))
            {
                Execute("CollectTaskResult", _job.CurrentJobProgramPath, fileName, paras);
            }
        }

19 Source : SwiftProcess.cs
with GNU General Public License v3.0
from bosima

public void SplitJob(CancellationToken cancellationToken = default(CancellationToken))
        {
            // todo 增加作业空间路径参数,因为程序文件只有1份了,具体作业执行时需要获取对应的配置和需求

            // 当前作业执行命令
            var fileName = _job.FileName;
            var paras = string.Format("-d -jr {0} -jn {1} -jp {2}", _job.Id, _job.Name, _job.CurrentJobSpacePath);

            var commandParas = FormatProcessCommandParas(fileName, paras);
            fileName = commandParas.Item1;
            paras = commandParas.Item2;

            var commandLine = string.Format("{0}:{1}:{2}", _job.CurrentJobProgramPath, fileName, paras);

            LogWriter.Write(string.Format("SwiftProcess->SplitJob Command: {0}", commandLine), Log.LogLevel.Debug);

            using (var ctsTokenRegistion = cancellationToken.Register(Kill))
            {
                Execute("SplitJob", _job.CurrentJobProgramPath, fileName, paras);
            }
        }

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 : DownloadCache.cs
with MIT License
from BretJohnson

protected virtual async Task<byte[]> DownloadAsync(string url, CancellationToken token, HttpClient client, ILoadableImageSource imageSource, DownloadInformation downloadInfo)
        {
            await Task.Delay(25, token).ConfigureAwait(false);
            token.ThrowIfCancellationRequested();

            using (var httpHeadersTimeoutTokenSource = new CancellationTokenSource())
            using (var headersTimeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, httpHeadersTimeoutTokenSource.Token))
            {
                httpHeadersTimeoutTokenSource.CancelAfter(TimeSpan.FromSeconds(_imageLoader.HttpHeadersTimeout));

                try
                {
                    CancellationToken headerTimeoutToken = headersTimeoutTokenSource.Token;

                    using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, headerTimeoutToken).ConfigureAwait(false))
                    {
                        headerTimeoutToken.ThrowIfCancellationRequested();

                        if (!response.IsSuccessStatusCode)
                        {
                            if (response.Content == null)
                                throw new DownloadHttpStatusCodeException(response.StatusCode);

                            using (response.Content)
                            {
                                string content = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);
                                throw new DownloadHttpStatusCodeException(response.StatusCode, content);
                            }
                        }

                        if (response.Content == null)
                            throw new DownloadException("No content");

                        string? mediaType = response.Content.Headers?.ContentType?.MediaType;
                        if (!string.IsNullOrWhiteSpace(mediaType) && !mediaType!.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
                        {
                            if (InvalidContentTypes.Any(v => mediaType.StartsWith(v, StringComparison.OrdinalIgnoreCase)))
                                throw new DownloadException($"Invalid response content type ({mediaType})");
                        }

                        if (_imageLoader.TryToReadDiskCacheDurationFromHttpHeaders
                            && response.Headers?.CacheControl?.MaxAge != null && response.Headers.CacheControl.MaxAge > TimeSpan.Zero)
                        {
                            downloadInfo.CacheValidity = response.Headers.CacheControl.MaxAge.Value;
                        }

                        using (var httpReadTimeoutTokenSource = new CancellationTokenSource())
                        using (var readTimeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, httpReadTimeoutTokenSource.Token))
                        {
                            CancellationToken readTimeoutToken = readTimeoutTokenSource.Token;
                            CancellationToken httpReadTimeoutToken = httpReadTimeoutTokenSource.Token;
                            int total = (int)(response.Content.Headers?.ContentLength ?? -1);

                            httpReadTimeoutTokenSource.CancelAfter(_imageLoader.HttpClient.Timeout);
                            readTimeoutToken.ThrowIfCancellationRequested();

                            try
                            {
                                using (var outputStream = new MemoryStream())
                                using (var sourceStream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false))
                                {
                                    httpReadTimeoutToken.Register(() => sourceStream.TryDispose());

                                    int totalRead = 0;
                                    byte[] buffer = new byte[_imageLoader.HttpReadBufferSize];
                                    int read = 0;
                                    int currentProgress = 1;

#if LATER
                                    imageSource.RaiseDownloadProgress(new DownloadProgressEventArgs(currentProgress));
#endif

                                    while ((read = await sourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
                                    {
                                        readTimeoutToken.ThrowIfCancellationRequested();
                                        outputStream.Write(buffer, 0, read);
                                        totalRead += read;

                                        if (total > 0)
                                            currentProgress = totalRead * 100 / total;
                                        else currentProgress = ++currentProgress;

                                        if (currentProgress < 1)
                                            currentProgress = 1;
                                        if (currentProgress > 99)
                                            currentProgress = 99;

#if LATER
                                        imageSource.RaiseDownloadProgress(new DownloadProgressEventArgs(currentProgress));
#endif
                                    }

                                    if (outputStream.Length == 0)
                                        throw new DownloadException("Zero length stream");

                                    if (outputStream.Length < 32)
                                        throw new DownloadException("Invalid stream");

                                    currentProgress = 100;
#if LATER
                                    imageSource.RaiseDownloadProgress(new DownloadProgressEventArgs(currentProgress));
#endif

                                    return outputStream.ToArray();
                                }
                            }
                            catch (Exception ex) when (ex is OperationCanceledException || ex is ObjectDisposedException)
                            {
                                if (httpReadTimeoutTokenSource.IsCancellationRequested)
                                    throw new DownloadReadTimeoutException();

                                throw;
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    if (httpHeadersTimeoutTokenSource.IsCancellationRequested)
                        throw new DownloadHeadersTimeoutException();
                    else
                        throw;
                }
            }
        }

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 : EventAggregator.cs
with MIT License
from btcpayserver

public async Task<T> WaitNext<T>(Func<T, bool> predicate, CancellationToken cancellation = default(CancellationToken))
        {
            TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
            using var subscription = Subscribe<T>((a, b) => { if (predicate(b)) { tcs.TrySetResult(b); a.Unsubscribe(); } });
            using (cancellation.Register(() => { tcs.TrySetCanceled(); }))
            {
                return await tcs.Task.ConfigureAwait(false);
            }
        }

19 Source : SSHClientExtensions.cs
with MIT License
from btcpayserver

public static async Task<SshClient> ConnectAsync(this SSHSettings sshSettings, CancellationToken cancellationToken = default)
        {
            if (sshSettings == null)
                throw new ArgumentNullException(nameof(sshSettings));
            TaskCompletionSource<SshClient> tcs = new TaskCompletionSource<SshClient>(TaskCreationOptions.RunContinuationsAsynchronously);
            new Thread(() =>
            {
                SshClient sshClient = null;
                try
                {
                    sshClient = new SshClient(sshSettings.CreateConnectionInfo());
                    sshClient.HostKeyReceived += (object sender, Renci.SshNet.Common.HostKeyEventArgs e) =>
                    {
                        if (sshSettings.TrustedFingerprints.Count == 0)
                        {
                            e.CanTrust = true;
                        }
                        else
                        {
                            e.CanTrust = sshSettings.IsTrustedFingerprint(e.FingerPrint, e.HostKey);
                        }
                    };
                    sshClient.Connect();
                    tcs.TrySetResult(sshClient);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                    try
                    {
                        sshClient?.Dispose();
                    }
                    catch { }
                }
            })
            { IsBackground = true }.Start();

            using (cancellationToken.Register(() => { tcs.TrySetCanceled(); }))
            {
                return await tcs.Task;
            }
        }

19 Source : MockDelay.cs
with MIT License
from btcpayserver

public async Task Wait(TimeSpan delay, CancellationToken cancellation)
        {
            WaitObj w = new WaitObj();
            w.Expiration = _Now + delay;
            w.CTS = new TaskCompletionSource<bool>();
            using (cancellation.Register(() =>
             {
                 w.CTS.TrySetCanceled();
             }))
            {
                lock (waits)
                {
                    waits.Add(w);
                }
                await w.CTS.Task;
            }
        }

19 Source : ProcessRunner.cs
with MIT License
from btcpayserver

public async Task<int> RunAsync(ProcessSpec processSpec, CancellationToken cancellationToken)
        {
            if (processSpec == null)
                throw new ArgumentNullException(nameof(processSpec));

            int exitCode;

            var stopwatch = new Stopwatch();

            using (var process = CreateProcess(processSpec))
            using (var processState = new ProcessState(process, _reporter))
            {
                cancellationToken.Register(() => processState.TryKill());

                var readOutput = false;
                var readError = false;
                if (processSpec.IsErrorCaptured)
                {
                    readError = true;
                    process.ErrorDataReceived += (_, a) =>
                    {
                        if (!string.IsNullOrEmpty(a.Data))
                        {
                            processSpec.ErrorCapture.AddLine(a.Data);
                        }
                    };
                }
                if (processSpec.IsOutputCaptured)
                {
                    readOutput = true;
                    process.OutputDataReceived += (_, a) =>
                    {
                        if (!string.IsNullOrEmpty(a.Data))
                        {
                            processSpec.OutputCapture.AddLine(a.Data);
                        }
                    };
                }

                stopwatch.Start();
                process.Start();

                _reporter.Verbose($"Started '{processSpec.Executable}' '{process.StartInfo.Arguments}' with process id {process.Id}");

                if (readOutput)
                {
                    process.BeginOutputReadLine();
                }
                if (readError)
                {
                    process.BeginErrorReadLine();
                }

                await processState.Task;

                exitCode = process.ExitCode;
                stopwatch.Stop();
                _reporter.Verbose($"Process id {process.Id} ran for {stopwatch.ElapsedMilliseconds}ms");
            }

            return exitCode;
        }

19 Source : CLightningClient.cs
with MIT License
from btcpayserver

internal async Task<T> SendCommandAsync<T>(string command, object[] parameters = null, bool noReturn = false, bool isArray = false, CancellationToken cancellation = default(CancellationToken))
		{
			parameters = parameters ?? Array.Empty<string>();
			using (Socket socket = await Connect())
			{
				using (var networkStream = new NetworkStream(socket))
				{
					using (var textWriter = new StreamWriter(networkStream, UTF8, 1024 * 10, true))
					{
						using (var jsonWriter = new JsonTextWriter(textWriter))
						{
							var req = new JObject();
							req.Add("id", 0);
							req.Add("method", command);
							req.Add("params", new JArray(parameters));
							await req.WriteToAsync(jsonWriter, cancellation);
							await jsonWriter.FlushAsync(cancellation);
						}
						await textWriter.FlushAsync();
					}
					await networkStream.FlushAsync(cancellation);
					using (var textReader = new StreamReader(networkStream, UTF8, false, 1024 * 10, true))
					{
						using (var jsonReader = new JsonTextReader(textReader))
						{
							var resultAsync = JObject.LoadAsync(jsonReader, cancellation);

							// without this hack resultAsync is blocking even if cancellation happen
							using (cancellation.Register(() =>
							 {
								 socket.Dispose();
							 }))
							{
								try
								{

									var result = await resultAsync;
									var error = result.Property("error");
									if (error != null)
									{
										throw new LightningRPCException(error.Value["message"].Value<string>(), error.Value["code"].Value<int>());
									}
									if (noReturn)
										return default(T);
									if (isArray)
									{
										return result["result"].Children().First().Children().First().ToObject<T>();
									}
									return result["result"].ToObject<T>();
								}
								catch when (cancellation.IsCancellationRequested)
								{
									cancellation.ThrowIfCancellationRequested();
									throw new NotSupportedException(); // impossible
								}
							}
						}
					}
				}
			}
		}

19 Source : CefCookieManager.cs
with MIT License
from CefNet

public async Task<bool> FlushStoreAsync(CancellationToken cancellationToken = default)
		{
			bool result;
			var tcs = new TaskCompletionSource<int>();
			using (cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				cancellationToken.ThrowIfCancellationRequested();
				result = this.FlushStore(new CefCompletionCallbackImpl(tcs.TrySetResult));
				await tcs.Task.ConfigureAwait(false);
			}
			return result;
		}

19 Source : CefRequestContext.cs
with MIT License
from CefNet

public async Task ClearHttpAuthCredentialsAsync(CancellationToken cancellationToken = default)
		{
			var tcs = new TaskCompletionSource<int>();
			using (cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				cancellationToken.ThrowIfCancellationRequested();
				this.ClearHttpAuthCredentials(new CefCompletionCallbackImpl(tcs.TrySetResult));
				await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefRequestContext.cs
with MIT License
from CefNet

public async Task ClearCertificateExceptionsAsync(CancellationToken cancellationToken = default)
		{
			var tcs = new TaskCompletionSource<int>();
			using (cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				cancellationToken.ThrowIfCancellationRequested();
				this.ClearCertificateExceptions(new CefCompletionCallbackImpl(tcs.TrySetResult));
				await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefRequestContext.cs
with MIT License
from CefNet

public async Task CloseAllConnectionsAsync(CancellationToken cancellationToken = default)
		{
			var tcs = new TaskCompletionSource<int>();
			using (cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				cancellationToken.ThrowIfCancellationRequested();
				this.CloseAllConnections(new CefCompletionCallbackImpl(tcs.TrySetResult));
				await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefRequestContext.cs
with MIT License
from CefNet

public async Task<CefCookieManager> GetCookieManagerAsync(CancellationToken cancellationToken = default)
		{
			CefCookieManager cookieManager;
			var tcs = new TaskCompletionSource<int>();
			using (cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				cancellationToken.ThrowIfCancellationRequested();
				cookieManager = this.GetCookieManager(new CefCompletionCallbackImpl(tcs.TrySetResult));
				await tcs.Task.ConfigureAwait(false);
			}
			return cookieManager;
		}

19 Source : CefRequestContext.cs
with MIT License
from CefNet

public async Task<CefMediaRouter> GetMediaRouterAsync(CancellationToken cancellationToken = default)
		{
			CefMediaRouter mediaRouter;
			var tcs = new TaskCompletionSource<int>();
			using (cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				cancellationToken.ThrowIfCancellationRequested();
				mediaRouter = this.GetMediaRouter(new CefCompletionCallbackImpl(tcs.TrySetResult));
				await tcs.Task.ConfigureAwait(false);
			}
			return mediaRouter;
		}

19 Source : CefNetStringVisitor.cs
with MIT License
from CefNet

public async Task<string> GetAsync(CancellationToken cancellationToken)
		{
			using (cancellationToken.Register(Cancel))
			{
				return await _completion.Task.ConfigureAwait(false);
			}
		}

19 Source : CefNetApi.cs
with MIT License
from CefNet

public static async Task<T> SendAsync<T>(CefThreadId threadId, Func<T> func, CancellationToken cancellationToken)
		{
			if (func == null)
				throw new ArgumentNullException(nameof(func));

			var tcs = new TaskCompletionSource<T>();
			var internalAction = new Action(() =>
			{
				if (cancellationToken.IsCancellationRequested)
				{
					tcs.SetCanceled();
				}
				else
				{
					T result = default;
					try
					{
						result = func();
					}
					catch (Exception e)
					{
						tcs.SetException(e);
						return;
					}
					tcs.SetResult(result);
				}
			});

			if (!Post(threadId, internalAction))
				throw new InvalidOperationException();

			if (!cancellationToken.CanBeCanceled)
				return await tcs.Task.ConfigureAwait(false);

			using (var reg = cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				return await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefNetWebRequest.cs
with MIT License
from CefNet

public async Task SendAsync(CefRequest request, CefRequestContext context, CancellationToken cancellationToken)
		{
			if (CefNetApplication.ProcessType != ProcessType.Main && context != null)
				throw new ArgumentOutOfRangeException(nameof(context));

			if (Interlocked.CompareExchange(ref _activeOperation, new RequestOperation(), null) != null)
				throw new InvalidOperationException();

			_request = request;
			_response = null;
			_exception = null;
			if (_stream != null)
			{
				_stream.Dispose();
				_stream = null;
			}
			_requestStatus = CefUrlRequestStatus.Unknown;
			this.RequestError = CefErrorCode.None;
			this.ResponseWasCached = false;
			this.IsCompleted = false;

			try
			{
				_activeOperation.request = await CreateUrlRequest(request, context, cancellationToken).ConfigureAwait(false);
				using (cancellationToken.Register(Abort))
				{
					await this;
				}
			}
			finally
			{
				Interlocked.Exchange(ref _activeOperation, null);
			}

			Exception exception = Volatile.Read(ref _exception);
			if (exception is null)
				return;

			ExceptionDispatchInfo.Capture(exception).Throw();
		}

19 Source : CefNetApi.cs
with MIT License
from CefNet

public static async Task SendAsync(CefThreadId threadId, Action action, CancellationToken cancellationToken)
		{
			if (action == null)
				throw new ArgumentNullException(nameof(action));

			var tcs = new TaskCompletionSource<bool>();
			var internalAction = new Action(() =>
			{
				if (cancellationToken.IsCancellationRequested)
				{
					tcs.SetCanceled();
				}
				else
				{
					try
					{
						action();
					}
					catch (Exception e)
					{
						tcs.SetException(e);
						return;
					}
					tcs.SetResult(true);
				}
			});

			if (!Post(threadId, internalAction))
				throw new InvalidOperationException();

			if (cancellationToken.CanBeCanceled)
			{
				using (var reg = cancellationToken.Register(() => tcs.TrySetCanceled()))
				{
					await tcs.Task.ConfigureAwait(false);
				}
			}
			else
			{
				await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefNetApi.cs
with MIT License
from CefNet

public static async Task<T> SendAsync<T>(CefThreadId threadId, Func<T> func, int delayMs, CancellationToken cancellationToken)
		{
			if (func == null)
				throw new ArgumentNullException(nameof(func));

			var tcs = new TaskCompletionSource<T>();
			var internalAction = new Action(() =>
			{
				if (cancellationToken.IsCancellationRequested)
				{
					tcs.SetCanceled();
				}
				else
				{
					T result = default;
					try
					{
						result = func();
					}
					catch (Exception e)
					{
						tcs.SetException(e);
						return;
					}
					tcs.SetResult(result);
				}
			});

			if (!Post(threadId, internalAction, delayMs))
				throw new InvalidOperationException();

			if (!cancellationToken.CanBeCanceled)
				return await tcs.Task.ConfigureAwait(false);

			using (var reg = cancellationToken.Register(() => tcs.TrySetCanceled()))
			{
				return await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefNetApi.cs
with MIT License
from CefNet

public static async Task SendAsync(CefThreadId threadId, Action action, int delayMs, CancellationToken cancellationToken)
		{
			if (action == null)
				throw new ArgumentNullException(nameof(action));

			var tcs = new TaskCompletionSource<bool>();
			var internalAction = new Action(() =>
			{
				if (cancellationToken.IsCancellationRequested)
				{
					tcs.SetCanceled();
				}
				else
				{
					try
					{
						action();
					}
					catch (Exception e)
					{
						tcs.SetException(e);
						return;
					}
					tcs.SetResult(true);
				}
			});

			if (!Post(threadId, internalAction))
				throw new InvalidOperationException();

			if (cancellationToken.CanBeCanceled)
			{
				using (var reg = cancellationToken.Register(() => tcs.TrySetCanceled()))
				{
					await tcs.Task.ConfigureAwait(false);
				}
			}
			else
			{
				await tcs.Task.ConfigureAwait(false);
			}
		}

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

public async Task StartAndAwaitReconnectionAsync(CancellationToken cancel)
		{
			await StartAsync(cancel).ConfigureAwait(false);
			using var ctr = cancel.Register(() => Success.SetResult(null));
			await Success.Task.ConfigureAwait(false);

			try
			{
				using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(21));
				await StopAsync(cts.Token).ConfigureAwait(false);
			}
			catch (Exception ex)
			{
				Logger.LogError(ex);
			}
			Dispose();
		}

19 Source : JdbcCommand.cs
with MIT License
from chequer-io

public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            cancellationToken.Register(Cancel);

            await using var dbDataReader = await ExecuteDbDataReaderAsync(CommandBehavior.Default, cancellationToken).ConfigureAwait(false);

            while (await dbDataReader.NextResultAsync(cancellationToken).ConfigureAwait(false))
            {
            }

            return dbDataReader.RecordsAffected;
        }

19 Source : JdbcCommand.cs
with MIT License
from chequer-io

public override async Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            cancellationToken.Register(Cancel);
            object result = null;

            await using var dbDataReader = await ExecuteDbDataReaderAsync(CommandBehavior.Default, cancellationToken).ConfigureAwait(false);

            if (await dbDataReader.ReadAsync(cancellationToken).ConfigureAwait(false) && dbDataReader.FieldCount > 0)
            {
                result = dbDataReader.GetValue(0);
            }

            return result;
        }

19 Source : BasRemoteClient.cs
with MIT License
from CheshireCaat

public async Task Start()
        {
            await _engine.InitializeAsync().ConfigureAwait(false);

            var port = Rand.NextInt(10000, 20000);

            await _engine.StartAsync(port).ConfigureAwait(false);
            await _socket.StartAsync(port).ConfigureAwait(false);

            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)))
            {
                using (cts.Token.Register(() => _completion.TrySetCanceled()))
                {
                    await _completion.Task.ConfigureAwait(false);
                }
            }
        }

19 Source : ObservableSourceStreamAdapter.cs
with MIT License
from ChilliCream

public async IAsyncEnumerator<object> GetAsyncEnumerator(
        CancellationToken cancellationToken = default)
    {
        try
        {
            _wait = new TaskCompletionSource<object>(RunContinuationsAsynchronously);
            cancellationToken.Register(() => _wait.TrySetCanceled());

            while (!cancellationToken.IsCancellationRequested)
            {
                if (_queue.TryDequeue(out T item))
                {
                    yield return item;
                }
                else if (_isCompleted)
                {
                    break;
                }
                else if (_wait.Task.IsCompleted)
                {
                    _wait = new TaskCompletionSource<object>();
                }
                else if (_queue.Count == 0)
                {
                    await _wait.Task.ConfigureAwait(false);
                }

                if (_exception is { })
                {
                    _isCompleted = true;
                    throw _exception;
                }
            }
        }
        finally
        {
            _subscription.Dispose();
        }
    }

19 Source : TcpCoapTransportLayer.cs
with MIT License
from chkr1011

public async Task ConnectAsync(CoapTransportLayerConnectOptions options, CancellationToken cancellationToken)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            Dispose();

            _tcpClient = new TcpClient();
            using (cancellationToken.Register(Dispose))
            {
                await _tcpClient.ConnectAsync(options.EndPoint.Address, options.EndPoint.Port).ConfigureAwait(false);
                _networkStream = _tcpClient.GetStream();
            }
        }

19 Source : DtlsCoapTransportLayer.cs
with MIT License
from chkr1011

public async Task ConnectAsync(CoapTransportLayerConnectOptions connectOptions, CancellationToken cancellationToken)
        {
            if (connectOptions == null)
            {
                throw new ArgumentNullException(nameof(connectOptions));
            }

            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                _udpTransport = new UdpTransport(connectOptions);
                var clientProtocol = new DtlsClientProtocol(_secureRandom);
                _dtlsClient = new DtlsClient(ConvertProtocolVersion(DtlsVersion), (PreSharedKey)Credentials);

                using (cancellationToken.Register(() => _udpTransport?.Close()))
                {
                    _dtlsTransport = await Task.Run(() => clientProtocol.Connect(_dtlsClient, _udpTransport), cancellationToken).ConfigureAwait(false);
                }
            }
            catch
            {
                _udpTransport?.Dispose();

                cancellationToken.ThrowIfCancellationRequested();
                
                throw new DtlsException($"Received alert {AlertDescription.GetText(_dtlsClient?.ReceivedAlert ?? 0xFF)}.", null)
                {
                    ReceivedAlert = _dtlsClient?.ReceivedAlert ?? 0xFF
                };
            }
        }

19 Source : DtlsCoapTransportLayer.cs
with MIT License
from chkr1011

public Task<int> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken)
        {
            if (buffer.Array == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            cancellationToken.ThrowIfCancellationRequested();

            using (cancellationToken.Register(() => _udpTransport.Close()))
            {
                try
                {
                    var received = _dtlsTransport.Receive(buffer.Array, buffer.Offset, buffer.Count, 0);
                    return Task.FromResult(received);
                }
                catch (ObjectDisposedException)
                {
                    return Task.FromResult(0);
                }
                catch (SocketException)
                {
                    return Task.FromResult(0);
                }
            }
        }

19 Source : CrossPlatformSocket.cs
with MIT License
from chkr1011

public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken)
        {
            if (host is null) throw new ArgumentNullException(nameof(host));

            try
            {
                _networkStream?.Dispose();

                // Workaround for: https://github.com/dotnet/corefx/issues/24430
                using (cancellationToken.Register(() => _socket.Dispose()))
                {
                    cancellationToken.ThrowIfCancellationRequested();

#if NET452 || NET461
                    await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, host, port, null).ConfigureAwait(false);
#else
                    await _socket.ConnectAsync(host, port).ConfigureAwait(false);
#endif
                    _networkStream = new NetworkStream(_socket, true);
                }
            }
            catch (SocketException socketException)
            {
                if (socketException.SocketErrorCode == SocketError.OperationAborted)
                {
                    throw new OperationCanceledException();
                }

                throw new MqttCommunicationException($"Error while connecting with host '{host}:{port}'.", socketException);
            }
            catch (ObjectDisposedException)
            {
                // This will happen when _socket.EndConnect gets called by Task library but the socket is already disposed.
                cancellationToken.ThrowIfCancellationRequested();
            }
        }

19 Source : MqttTcpChannel.cs
with MIT License
from chkr1011

public async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                var stream = _stream;

                if (stream == null)
                {
                    return 0;
                }

                if (!stream.CanRead)
                {
                    return 0;
                }

                // Workaround for: https://github.com/dotnet/corefx/issues/24430
                using (cancellationToken.Register(Dispose))
                {
                    return await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (ObjectDisposedException)
            {
                // Indicate a graceful socket close.
                return 0;
            }
            catch (IOException exception)
            {
                if (exception.InnerException is SocketException socketException)
                {
                    ExceptionDispatchInfo.Capture(socketException).Throw();
                }

                throw;
            }
        }

19 Source : MqttTcpChannel.cs
with MIT License
from chkr1011

public async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                // Workaround for: https://github.com/dotnet/corefx/issues/24430
                using (cancellationToken.Register(Dispose))
                {
                    var stream = _stream;

                    if (stream == null)
                    {
                        throw new MqttCommunicationException("The TCP connection is closed.");
                    }

                    await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (ObjectDisposedException)
            {
                throw new MqttCommunicationException("The TCP connection is closed.");
            }
            catch (IOException exception)
            {
                if (exception.InnerException is SocketException socketException)
                {
                    ExceptionDispatchInfo.Capture(socketException).Throw();
                }

                throw;
            }
        }

19 Source : MqttRpcClient.cs
with MIT License
from chkr1011

public async Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, CancellationToken cancellationToken)
        {
            if (methodName == null) throw new ArgumentNullException(nameof(methodName));

            if (!(_mqttClient.ApplicationMessageReceivedHandler is RpcAwareApplicationMessageReceivedHandler))
            {
                throw new InvalidOperationException("The application message received handler was modified.");
            }

            var topicNames = _options.TopicGenerationStrategy.CreateRpcTopics(new TopicGenerationContext
            {
                MethodName = methodName,
                QualityOfServiceLevel = qualityOfServiceLevel,
                MqttClient = _mqttClient,
                Options = _options
            });

            var requestTopic = topicNames.RequestTopic;
            var responseTopic = topicNames.ResponseTopic;

            if (string.IsNullOrWhiteSpace(requestTopic))
            {
                throw new MqttProtocolViolationException("RPC request topic is empty.");
            }

            if (string.IsNullOrWhiteSpace(responseTopic))
            {
                throw new MqttProtocolViolationException("RPC response topic is empty.");
            }

            var requestMessage = new MqttApplicationMessageBuilder()
                .WithTopic(requestTopic)
                .WithPayload(payload)
                .WithQualityOfServiceLevel(qualityOfServiceLevel)
                .Build();

            try
            {
#if NET452
                var awaitable = new TaskCompletionSource<byte[]>();
#else
                var awaitable = new TaskCompletionSource<byte[]>(TaskCreationOptions.RunContinuationsAsynchronously);
#endif
                
                if (!_waitingCalls.TryAdd(responseTopic, awaitable))
                {
                    throw new InvalidOperationException();
                }

                var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
                    .WithTopicFilter(responseTopic, qualityOfServiceLevel)
                    .Build();

                await _mqttClient.SubscribeAsync(subscribeOptions, cancellationToken).ConfigureAwait(false);
                await _mqttClient.PublishAsync(requestMessage, cancellationToken).ConfigureAwait(false);

                using (cancellationToken.Register(() => { awaitable.TrySetCanceled(); }))
                {
                    return await awaitable.Task.ConfigureAwait(false);
                }
            }
            finally
            {
                _waitingCalls.TryRemove(responseTopic, out _);

                await _mqttClient.UnsubscribeAsync(responseTopic).ConfigureAwait(false);
            }
        }

See More Examples