System.Threading.CancellationTokenSource.Dispose()

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

1156 Examples 7

19 Source : Dumper.cs
with MIT License
from 13xforever

public void Dispose()
        {
            driveStream?.Dispose();
            ((IDisposable)Decrypter)?.Dispose();
            Cts?.Dispose();
        }

19 Source : RecordStream.cs
with MIT License
from a1q123456

[RpcMethod("seek")]
        public async Task Seek([FromOptionalArgument] double milliSeconds)
        {
            var resetData = new AmfObject
            {
                {"level", "status" },
                {"code", "NetStream.Seek.Notify" },
                {"description", "Seeking stream." },
                {"details", "seek" }
            };
            var resetStatus = RtmpSession.CreateCommandMessage<OnStatusCommandMessage>();
            resetStatus.InfoObject = resetData;
            await MessageStream.SendMessageAsync(ChunkStream, resetStatus);

            _playCts?.Cancel();
            while (_playing == 1)
            {
                await Task.Yield();
            }

            var cts = new CancellationTokenSource();
            _playCts?.Dispose();
            _playCts = cts;
            await SeekAndPlay(milliSeconds, cts.Token);
        }

19 Source : RecordStream.cs
with MIT License
from a1q123456

[RpcMethod("play")]
        public async Task Play(
     [FromOptionalArgument] string streamName,
     [FromOptionalArgument] double start = -1,
     [FromOptionalArgument] double duration = -1,
     [FromOptionalArgument] bool reset = false)
        {
            _recordFile = new FileStream(_recordService.GetRecordFilename(streamName) + ".flv", FileMode.Open, FileAccess.Read);
            await FlvDemuxer.AttachStream(_recordFile);

            var resetData = new AmfObject
            {
                {"level", "status" },
                {"code", "NetStream.Play.Reset" },
                {"description", "Resetting and playing stream." },
                {"details", streamName }
            };
            var resetStatus = RtmpSession.CreateCommandMessage<OnStatusCommandMessage>();
            resetStatus.InfoObject = resetData;
            await MessageStream.SendMessageAsync(ChunkStream, resetStatus);

            var startData = new AmfObject
            {
                {"level", "status" },
                {"code", "NetStream.Play.Start" },
                {"description", "Started playing." },
                {"details", streamName }
            };

            var startStatus = RtmpSession.CreateCommandMessage<OnStatusCommandMessage>();
            startStatus.InfoObject = startData;
            await MessageStream.SendMessageAsync(ChunkStream, startStatus);
            var bandwidthLimit = new WindowAcknowledgementSizeMessage()
            {
                WindowSize = 500 * 1024
            };
            await RtmpSession.ControlMessageStream.SendMessageAsync(RtmpSession.ControlChunkStream, bandwidthLimit);
            VideoChunkStream = RtmpSession.CreateChunkStream();
            AudioChunkStream = RtmpSession.CreateChunkStream();

            var cts = new CancellationTokenSource();
            _playCts?.Dispose();
            _playCts = cts;
            start = Math.Max(start, 0);
            await SeekAndPlay(start / 1000, cts.Token);
        }

19 Source : RecordStream.cs
with MIT License
from a1q123456

[RpcMethod("pause")]
        public async Task Pause([FromOptionalArgument] bool isPause, [FromOptionalArgument] double milliseconds)
        {
            if (isPause)
            {
                _playCts?.Cancel();
                while (_playing == 1)
                {
                    await Task.Yield();
                }
            }
            else
            {
                var cts = new CancellationTokenSource();
                _playCts?.Dispose();
                _playCts = cts;
                await SeekAndPlay(milliseconds, cts.Token);
            }
        }

19 Source : Supervisor.cs
with MIT License
from a1q123456

private void ThreadEntry()
        {
            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    foreach (var kv in server.connectedSessions)
                    {
                        if (!sessionStates.TryGetValue(kv.Key, out var sessionState))
                        {
                            sessionState = new SessionState()
                            {
                                LastPing = DateTime.Now,
                                Session = kv.Value
                            };
                            sessionStates.Add(kv.Key, sessionState);
                        }
                        var session = kv.Value;
                        if (DateTime.Now - sessionState.LastPing >= pingInterval && sessionState.CancellationTokenSource == null)
                        {
                            sessionState.CancellationTokenSource = new CancellationTokenSource();
                            sessionState.CancellationTokenSource.CancelAfter((int)responseThreshole.TotalMilliseconds);
                            var pingTask = session.PingAsync(sessionState.CancellationTokenSource.Token);
                            pingTask.ContinueWith(tsk =>
                            {
                                sessionState.CancellationTokenSource.Dispose();
                                sessionState.CancellationTokenSource = null;
                                sessionState.LastPing = DateTime.Now;
                            }, TaskContinuationOptions.OnlyOnRanToCompletion);
                            pingTask.ContinueWith(tsk =>
                            {
                                sessionState.Session.Disconnect(new ExceptionalEventArgs("pingpong timeout"));
                                sessionState.CancellationTokenSource.Dispose();
                                sessionState.CancellationTokenSource = null;
                            }, TaskContinuationOptions.OnlyOnCanceled);
                        }
                    }
                    Thread.Sleep(1);
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch
            {

            }
        }

19 Source : TaskHelpers.cs
with MIT License
from abdullin

public static void SafeCancelAndDispose(this CancellationTokenSource source)
		{
			if (source != null)
			{
				try
				{
					if (!source.IsCancellationRequested)
					{
						source.Cancel();
					}
				}
				catch (ObjectDisposedException) { }
				finally
				{
					source.Dispose();
				}
			}
		}

19 Source : AudioDeviceHandler.cs
with MIT License
from ABTSoftware

public void Dispose()
        {
            if (_capture.CaptureState == CaptureState.Stopped)
            {
                _capture.Dispose();
                _device.Dispose();
            }
            else
            {
                Stop();
            }
            _cts.Cancel();
            _cts.Dispose();

        }

19 Source : HostContext.cs
with MIT License
from actions

private void Dispose(bool disposing)
        {
            // TODO: Dispose the trace listener also.
            if (disposing)
            {
                if (_loadContext != null)
                {
                    _loadContext.Unloading -= LoadContext_Unloading;
                    _loadContext = null;
                }
                _httpTraceSubscription?.Dispose();
                _diagListenerSubscription?.Dispose();
                _traceManager?.Dispose();
                _traceManager = null;

                _runnerShutdownTokenSource?.Dispose();
                _runnerShutdownTokenSource = null;

                base.Dispose();
            }
        }

19 Source : Runner.cs
with MIT License
from actions

private async Task<int> RunAsync(RunnerSettings settings, bool runOnce = false)
        {
            try
            {
                Trace.Info(nameof(RunAsync));
                _listener = HostContext.GetService<IMessageListener>();
                if (!await _listener.CreateSessionAsync(HostContext.RunnerShutdownToken))
                {
                    return Constants.Runner.ReturnCode.TerminatedError;
                }

                HostContext.WritePerfCounter("SessionCreated");

                _term.WriteLine($"Current runner version: '{BuildConstants.RunnerPackage.Version}'");
                _term.WriteLine($"{DateTime.UtcNow:u}: Listening for Jobs");

                IJobDispatcher jobDispatcher = null;
                CancellationTokenSource messageQueueLoopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(HostContext.RunnerShutdownToken);
                
                // Should we try to cleanup ephemeral runners
                bool runOnceJobCompleted = false;
                try
                {
                    var notification = HostContext.GetService<IJobNotification>();

                    notification.StartClient(settings.MonitorSocketAddress);

                    bool autoUpdateInProgress = false;
                    Task<bool> selfUpdateTask = null;
                    bool runOnceJobReceived = false;
                    jobDispatcher = HostContext.CreateService<IJobDispatcher>();

                    while (!HostContext.RunnerShutdownToken.IsCancellationRequested)
                    {
                        TaskAgentMessage message = null;
                        bool skipMessageDeletion = false;
                        try
                        {
                            Task<TaskAgentMessage> getNextMessage = _listener.GetNextMessageAsync(messageQueueLoopTokenSource.Token);
                            if (autoUpdateInProgress)
                            {
                                Trace.Verbose("Auto update task running at backend, waiting for getNextMessage or selfUpdateTask to finish.");
                                Task completeTask = await Task.WhenAny(getNextMessage, selfUpdateTask);
                                if (completeTask == selfUpdateTask)
                                {
                                    autoUpdateInProgress = false;
                                    if (await selfUpdateTask)
                                    {
                                        Trace.Info("Auto update task finished at backend, an runner update is ready to apply exit the current runner instance.");
                                        Trace.Info("Stop message queue looping.");
                                        messageQueueLoopTokenSource.Cancel();
                                        try
                                        {
                                            await getNextMessage;
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.Info($"Ignore any exception after cancel message loop. {ex}");
                                        }

                                        if (runOnce)
                                        {
                                            return Constants.Runner.ReturnCode.RunOnceRunnerUpdating;
                                        }
                                        else
                                        {
                                            return Constants.Runner.ReturnCode.RunnerUpdating;
                                        }
                                    }
                                    else
                                    {
                                        Trace.Info("Auto update task finished at backend, there is no available runner update needs to apply, continue message queue looping.");
                                    }
                                }
                            }

                            if (runOnceJobReceived)
                            {
                                Trace.Verbose("One time used runner has start running its job, waiting for getNextMessage or the job to finish.");
                                Task completeTask = await Task.WhenAny(getNextMessage, jobDispatcher.RunOnceJobCompleted.Task);
                                if (completeTask == jobDispatcher.RunOnceJobCompleted.Task)
                                {
                                    runOnceJobCompleted = true;
                                    Trace.Info("Job has finished at backend, the runner will exit since it is running under onetime use mode.");
                                    Trace.Info("Stop message queue looping.");
                                    messageQueueLoopTokenSource.Cancel();
                                    try
                                    {
                                        await getNextMessage;
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.Info($"Ignore any exception after cancel message loop. {ex}");
                                    }

                                    return Constants.Runner.ReturnCode.Success;
                                }
                            }

                            message = await getNextMessage; //get next message
                            HostContext.WritePerfCounter($"MessageReceived_{message.MessageType}");
                            if (string.Equals(message.MessageType, AgentRefreshMessage.MessageType, StringComparison.OrdinalIgnoreCase))
                            {
                                if (autoUpdateInProgress == false)
                                {
                                    autoUpdateInProgress = true;
                                    var runnerUpdateMessage = JsonUtility.FromString<AgentRefreshMessage>(message.Body);
                                    var selfUpdater = HostContext.GetService<ISelfUpdater>();
                                    selfUpdateTask = selfUpdater.SelfUpdate(runnerUpdateMessage, jobDispatcher, !runOnce && HostContext.StartupType != StartupType.Service, HostContext.RunnerShutdownToken);
                                    Trace.Info("Refresh message received, kick-off selfupdate background process.");
                                }
                                else
                                {
                                    Trace.Info("Refresh message received, skip autoupdate since a previous autoupdate is already running.");
                                }
                            }
                            else if (string.Equals(message.MessageType, JobRequestMessageTypes.PipelineAgentJobRequest, StringComparison.OrdinalIgnoreCase))
                            {
                                if (autoUpdateInProgress || runOnceJobReceived)
                                {
                                    skipMessageDeletion = true;
                                    Trace.Info($"Skip message deletion for job request message '{message.MessageId}'.");
                                }
                                else
                                {
                                    var jobMessage = StringUtil.ConvertFromJson<Pipelines.AgentJobRequestMessage>(message.Body);
                                    jobDispatcher.Run(jobMessage, runOnce);
                                    if (runOnce)
                                    {
                                        Trace.Info("One time used runner received job message.");
                                        runOnceJobReceived = true;
                                    }
                                }
                            }
                            else if (string.Equals(message.MessageType, JobCancelMessage.MessageType, StringComparison.OrdinalIgnoreCase))
                            {
                                var cancelJobMessage = JsonUtility.FromString<JobCancelMessage>(message.Body);
                                bool jobCancelled = jobDispatcher.Cancel(cancelJobMessage);
                                skipMessageDeletion = (autoUpdateInProgress || runOnceJobReceived) && !jobCancelled;

                                if (skipMessageDeletion)
                                {
                                    Trace.Info($"Skip message deletion for cancellation message '{message.MessageId}'.");
                                }
                            }
                            else
                            {
                                Trace.Error($"Received message {message.MessageId} with unsupported message type {message.MessageType}.");
                            }
                        }
                        finally
                        {
                            if (!skipMessageDeletion && message != null)
                            {
                                try
                                {
                                    await _listener.DeleteMessageAsync(message);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error($"Catch exception during delete message from message queue. message id: {message.MessageId}");
                                    Trace.Error(ex);
                                }
                                finally
                                {
                                    message = null;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (jobDispatcher != null)
                    {
                        await jobDispatcher.ShutdownAsync();
                    }

                    try
                    {
                        await _listener.DeleteSessionAsync();
                    }
                    catch (Exception ex) when (runOnce)
                    {
                        // ignore exception during delete session for ephemeral runner since the runner might already be deleted from the server side
                        // and the delete session call will ends up with 401.
                        Trace.Info($"Ignore any exception during DeleteSession for an ephemeral runner. {ex}");
                    }

                    messageQueueLoopTokenSource.Dispose();

                    if (settings.Ephemeral && runOnceJobCompleted)
                    {
                        var configManager = HostContext.GetService<IConfigurationManager>();
                        configManager.DeleteLocalRunnerConfig();
                    }
                }
            }
            catch (TaskAgentAccessTokenExpiredException)
            {
                Trace.Info("Runner OAuth token has been revoked. Shutting down.");
            }

            return Constants.Runner.ReturnCode.Success;
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public TaskResult Complete(TaskResult? result = null, string currentOperation = null, string resultCode = null)
        {
            if (result != null)
            {
                Result = result;
            }

            // report total delay caused by server throttling.
            if (_totalThrottlingDelayInMilliseconds > _throttlingDelayReportThreshold)
            {
                this.Warning($"The job has experienced {TimeSpan.FromMilliseconds(_totalThrottlingDelayInMilliseconds).TotalSeconds} seconds total delay caused by server throttling.");
            }

            _record.CurrentOperation = currentOperation ?? _record.CurrentOperation;
            _record.ResultCode = resultCode ?? _record.ResultCode;
            _record.FinishTime = DateTime.UtcNow;
            _record.PercentComplete = 100;
            _record.Result = _record.Result ?? TaskResult.Succeeded;
            _record.State = TimelineRecordState.Completed;

            _jobServerQueue.QueueTimelineRecordUpdate(_mainTimelineId, _record);

            // complete all detail timeline records.
            if (_detailTimelineId != Guid.Empty && _detailRecords.Count > 0)
            {
                foreach (var record in _detailRecords)
                {
                    record.Value.FinishTime = record.Value.FinishTime ?? DateTime.UtcNow;
                    record.Value.PercentComplete = record.Value.PercentComplete ?? 100;
                    record.Value.Result = record.Value.Result ?? TaskResult.Succeeded;
                    record.Value.State = TimelineRecordState.Completed;

                    _jobServerQueue.QueueTimelineRecordUpdate(_detailTimelineId, record.Value);
                }
            }

            if (Root != this)
            {
                // only dispose TokenSource for step level ExecutionContext
                _cancellationTokenSource?.Dispose();
            }

            _logger.End();

            // Skip if generated context name. Generated context names start with "__". After 3.2 the server will never send an empty context name.
            if (!string.IsNullOrEmpty(ContextName) && !ContextName.StartsWith("__", StringComparison.Ordinal))
            {
                Global.StepsContext.SetOutcome(ScopeName, ContextName, (Outcome ?? Result ?? TaskResult.Succeeded).ToActionResult());
                Global.StepsContext.SetConclusion(ScopeName, ContextName, (Result ?? TaskResult.Succeeded).ToActionResult());
            }

            return Result.Value;
        }

19 Source : VssHttpMessageHandler.cs
with MIT License
from actions

protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            VssTraceActivity traceActivity = VssTraceActivity.Current;

            var traceInfo = VssHttpMessageHandlerTraceInfo.GetTraceInfo(request);
            traceInfo?.TraceHandlerStartTime();

            if (!m_appliedClientCertificatesToTransportHandler &&
                request.RequestUri.Scheme == "https")
            {
                HttpClientHandler httpClientHandler = m_transportHandler as HttpClientHandler;
                if (httpClientHandler != null &&
                    this.Settings.ClientCertificateManager != null &&
                    this.Settings.ClientCertificateManager.ClientCertificates != null &&
                    this.Settings.ClientCertificateManager.ClientCertificates.Count > 0)
                {
                    httpClientHandler.ClientCertificates.AddRange(this.Settings.ClientCertificateManager.ClientCertificates);
                }
                m_appliedClientCertificatesToTransportHandler = true;
            }

            if (!m_appliedServerCertificateValidationCallbackToTransportHandler &&
                request.RequestUri.Scheme == "https")
            {
                HttpClientHandler httpClientHandler = m_transportHandler as HttpClientHandler;
                if (httpClientHandler != null &&
                    this.Settings.ServerCertificateValidationCallback != null)
                {
                    httpClientHandler.ServerCertificateCustomValidationCallback = this.Settings.ServerCertificateValidationCallback;
                }
                m_appliedServerCertificateValidationCallbackToTransportHandler = true;
            }

            // The .NET Core 2.1 runtime switched its HTTP default from HTTP 1.1 to HTTP 2.
            // This causes problems with some versions of the Curl handler on Linux.
            // See GitHub issue https://github.com/dotnet/corefx/issues/32376
            if (Settings.UseHttp11)
            {
                request.Version = HttpVersion.Version11;
            }

            IssuedToken token = null;
            IssuedTokenProvider provider;
            if (this.Credentials.TryGetTokenProvider(request.RequestUri, out provider))
            {
                token = provider.CurrentToken;
            }

            // Add ourselves to the message so the underlying token issuers may use it if necessary
            request.Properties[VssHttpMessageHandler.PropertyName] = this;

            Boolean succeeded = false;
            Boolean lastResponseDemandedProxyAuth = false;
            Int32 retries = m_maxAuthRetries;
            HttpResponseMessage response = null;
            HttpResponseMessageWrapper responseWrapper;
            CancellationTokenSource tokenSource = null;

            try
            {
                tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

                if (this.Settings.SendTimeout > TimeSpan.Zero)
                {
                    tokenSource.CancelAfter(this.Settings.SendTimeout);
                }

                do
                {
                    if (response != null)
                    {
                        response.Dispose();
                    }

                    ApplyHeaders(request);

                    // In the case of a Windows token, only apply it to the web proxy if it
                    // returned a 407 Proxy Authentication Required. If we didn't get this
                    // status code back, then the proxy (if there is one) is clearly working fine,
                    // so we shouldn't mess with its credentials.
                    ApplyToken(request, token, applyICredentialsToWebProxy: lastResponseDemandedProxyAuth);
                    lastResponseDemandedProxyAuth = false;

                    // The WinHttpHandler will chunk any content that does not have a computed length which is
                    // not what we want. By loading into a buffer up-front we bypreplaced this behavior and there is
                    // no difference in the normal HttpClientHandler behavior here since this is what they were
                    // already doing.
                    await BufferRequestContentAsync(request, tokenSource.Token).ConfigureAwait(false);

                    traceInfo?.TraceBufferedRequestTime();

                    // ConfigureAwait(false) enables the continuation to be run outside any captured 
                    // SyncronizationContext (such as ASP.NET's) which keeps things from deadlocking...
                    response = await m_messageInvoker.SendAsync(request, tokenSource.Token).ConfigureAwait(false);

                    traceInfo?.TraceRequestSendTime();

                    // Now buffer the response content if configured to do so. In general we will be buffering
                    // the response content in this location, except in the few cases where the caller has 
                    // specified HttpCompletionOption.ResponseHeadersRead.
                    // Trace content type in case of error
                    await BufferResponseContentAsync(request, response, () => $"[ContentType: {response.Content.GetType().Name}]", tokenSource.Token).ConfigureAwait(false);

                    traceInfo?.TraceResponseContentTime();

                    responseWrapper = new HttpResponseMessageWrapper(response);

                    if (!this.Credentials.IsAuthenticationChallenge(responseWrapper))
                    {
                        // Validate the token after it has been successfully authenticated with the server.
                        if (provider != null)
                        {
                            provider.ValidateToken(token, responseWrapper);
                        }

                        // Make sure that once we can authenticate with the service that we turn off the 
                        // Expect100Continue behavior to increase performance.
                        this.ExpectContinue = false;
                        succeeded = true;
                        break;
                    }
                    else
                    {
                        // In the case of a Windows token, only apply it to the web proxy if it
                        // returned a 407 Proxy Authentication Required. If we didn't get this
                        // status code back, then the proxy (if there is one) is clearly working fine,
                        // so we shouldn't mess with its credentials.
                        lastResponseDemandedProxyAuth = responseWrapper.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;

                        // Invalidate the token and ensure that we have the correct token provider for the challenge
                        // which we just received
                        VssHttpEventSource.Log.AuthenticationFailed(traceActivity, response);

                        if (provider != null)
                        {
                            provider.InvalidateToken(token);
                        }

                        // Ensure we have an appropriate token provider for the current challenge
                        provider = this.Credentials.CreateTokenProvider(request.RequestUri, responseWrapper, token);

                        // Make sure we don't invoke the provider in an invalid state
                        if (provider == null)
                        {
                            VssHttpEventSource.Log.IssuedTokenProviderNotFound(traceActivity);
                            break;
                        }
                        else if (provider.GetTokenIsInteractive && this.Credentials.PromptType == CredentialPromptType.DoNotPrompt)
                        {
                            VssHttpEventSource.Log.IssuedTokenProviderPromptRequired(traceActivity, provider);
                            break;
                        }

                        // If the user has already tried once but still unauthorized, stop retrying. The main scenario for this condition
                        // is a user typed in a valid credentials for a hosted account but the replacedociated idenreplacedy does not have 
                        // access. We do not want to continually prompt 3 times without telling them the failure reason. In the 
                        // next release we should rethink about presenting user the failure and options between retries.
                        IEnumerable<String> headerValues;
                        Boolean hasAuthenticateError =
                            response.Headers.TryGetValues(HttpHeaders.VssAuthenticateError, out headerValues) &&
                            !String.IsNullOrEmpty(headerValues.FirstOrDefault());

                        if (retries == 0 || (retries < m_maxAuthRetries && hasAuthenticateError))
                        {
                            break;
                        }

                        // Now invoke the provider and await the result
                        token = await provider.GetTokenAsync(token, tokenSource.Token).ConfigureAwait(false);

                        // I always see 0 here, but the method above could take more time so keep for now
                        traceInfo?.TraceGetTokenTime();

                        // If we just received a token, lets ask the server for the VSID
                        request.Headers.Add(HttpHeaders.VssUserData, String.Empty);

                        retries--;
                    }
                }
                while (retries >= 0);

                if (traceInfo != null)
                {
                    traceInfo.TokenRetries = m_maxAuthRetries - retries;
                }

                // We're out of retries and the response was an auth challenge -- then the request was unauthorized
                // and we will throw a strongly-typed exception with a friendly error message.
                if (!succeeded && response != null && this.Credentials.IsAuthenticationChallenge(responseWrapper))
                {
                    String message = null;
                    IEnumerable<String> serviceError;

                    if (response.Headers.TryGetValues(HttpHeaders.TfsServiceError, out serviceError))
                    {
                        message = UriUtility.UrlDecode(serviceError.FirstOrDefault());
                    }
                    else
                    {
                        message = CommonResources.VssUnauthorized(request.RequestUri.GetLeftPart(UriPartial.Authority));
                    }

                    // Make sure we do not leak the response object when raising an exception
                    if (response != null)
                    {
                        response.Dispose();
                    }

                    VssHttpEventSource.Log.HttpRequestUnauthorized(traceActivity, request, message);
                    VssUnauthorizedException unauthorizedException = new VssUnauthorizedException(message);

                    if (provider != null)
                    {
                        unauthorizedException.Data.Add(CredentialsType, provider.CredentialType);
                    }

                    throw unauthorizedException;
                }

                return response;
            }
            catch (OperationCanceledException ex)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    VssHttpEventSource.Log.HttpRequestCancelled(traceActivity, request);
                    throw;
                }
                else
                {
                    VssHttpEventSource.Log.HttpRequestTimedOut(traceActivity, request, this.Settings.SendTimeout);
                    throw new TimeoutException(CommonResources.HttpRequestTimeout(this.Settings.SendTimeout), ex);
                }
            }
            finally
            {
                // We always dispose of the token source since otherwise we leak resources if there is a timer pending
                if (tokenSource != null)
                {
                    tokenSource.Dispose();
                }

                traceInfo?.TraceTrailingTime();
            }
        }

19 Source : ActionManifestManagerL0.cs
with MIT License
from actions

private void Setup([CallerMemberName] string name = "")
        {
            _ecTokenSource?.Dispose();
            _ecTokenSource = new CancellationTokenSource();

            // Test host context.
            _hc = new TestHostContext(this, name);

            _ec = new Mock<IExecutionContext>();
            _ec.Setup(x => x.Global)
                .Returns(new GlobalContext
                {
                    FileTable = new List<String>(),
                    Variables = new Variables(_hc, new Dictionary<string, VariableValue>()),
                    WriteDebug = true,
                });
            _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
            _ec.Setup(x => x.ExpressionValues).Returns(new DictionaryContextData());
            _ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>());
            _ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"{tag}{message}"); });
            _ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });
        }

19 Source : ActionRunnerL0.cs
with MIT License
from actions

private void Setup([CallerMemberName] string name = "")
        {
            _ecTokenSource?.Dispose();
            _ecTokenSource = new CancellationTokenSource();

            // Test host context.
            _hc = new TestHostContext(this, name);

            var actionInputs = new MappingToken(null, null, null);
            actionInputs.Add(new StringToken(null, null, null, "input1"), new StringToken(null, null, null, "input1"));
            actionInputs.Add(new StringToken(null, null, null, "input2"), new StringToken(null, null, null, ""));
            actionInputs.Add(new StringToken(null, null, null, "input3"), new StringToken(null, null, null, "github"));
            var actionDefinition = new Definition()
            {
                Directory = _hc.GetDirectory(WellKnownDirectory.Work),
                Data = new ActionDefinitionData()
                {
                    Name = name,
                    Description = name,
                    Inputs = actionInputs,
                    Execution = new ScriptActionExecutionData()
                }
            };

            // Mocks.
            _actionManager = new Mock<IActionManager>();
            _actionManager.Setup(x => x.LoadAction(It.IsAny<IExecutionContext>(), It.IsAny<ActionStep>())).Returns(actionDefinition);

            _handlerFactory = new Mock<IHandlerFactory>();
            _defaultStepHost = new Mock<IDefaultStepHost>();
            _actionManifestManager = new ActionManifestManager();
            _fileCommandManager = new Mock<IFileCommandManager>();
            _actionManifestManager.Initialize(_hc);

            var githubContext = new GitHubContext();
            githubContext.Add("event", JToken.Parse("{\"foo\":\"bar\"}").ToPipelineContextData());
            _context.Add("github", githubContext);

#if OS_WINDOWS
            _context["env"] = new DictionaryContextData();
#else
            _context["env"] = new CaseSensitiveDictionaryContextData();
#endif

            _ec = new Mock<IExecutionContext>();
            _ec.Setup(x => x.Global).Returns(new GlobalContext());
            _ec.Setup(x => x.ExpressionValues).Returns(_context);
            _ec.Setup(x => x.ExpressionFunctions).Returns(new List<IFunctionInfo>());
            _ec.Setup(x => x.IntraActionState).Returns(new Dictionary<string, string>());
            _ec.Object.Global.EnvironmentVariables = new Dictionary<string, string>();
            _ec.Object.Global.FileTable = new List<String>();
            _ec.Setup(x => x.SetGitHubContext(It.IsAny<string>(), It.IsAny<string>()));
            _ec.Setup(x => x.GetGitHubContext(It.IsAny<string>())).Returns("{\"foo\":\"bar\"}");
            _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
            _ec.Object.Global.Variables = new Variables(_hc, new Dictionary<string, VariableValue>());
            _ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); });
            _ec.Setup(x => x.AddIssue(It.IsAny<Issue>(), It.IsAny<string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });

            _hc.SetSingleton<IActionManager>(_actionManager.Object);
            _hc.SetSingleton<IHandlerFactory>(_handlerFactory.Object);
            _hc.SetSingleton<IActionManifestManager>(_actionManifestManager);

            _hc.EnqueueInstance<IDefaultStepHost>(_defaultStepHost.Object);

            _hc.EnqueueInstance(_fileCommandManager.Object);

            // Instance to test.
            _actionRunner = new ActionRunner();
            _actionRunner.Initialize(_hc);
            _actionRunner.ExecutionContext = _ec.Object;
        }

19 Source : JobExtensionL0.cs
with MIT License
from actions

private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);
            _jobEc = new Runner.Worker.ExecutionContext();
            _actionManager = new Mock<IActionManager>();
            _jobServerQueue = new Mock<IJobServerQueue>();
            _config = new Mock<IConfigurationStore>();
            _logger = new Mock<IPagingLogger>();
            _containerProvider = new Mock<IContainerOperationProvider>();
            _diagnosticLogManager = new Mock<IDiagnosticLogManager>();
            _directoryManager = new Mock<IPipelineDirectoryManager>();
            _directoryManager.Setup(x => x.PrepareDirectory(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.WorkspaceOptions>()))
                             .Returns(new TrackingConfig() { PipelineDirectory = "runner", WorkspaceDirectory = "runner/runner" });

            IActionRunner step1 = new ActionRunner();
            IActionRunner step2 = new ActionRunner();
            IActionRunner step3 = new ActionRunner();
            IActionRunner step4 = new ActionRunner();
            IActionRunner step5 = new ActionRunner();

            _logger.Setup(x => x.Setup(It.IsAny<Guid>(), It.IsAny<Guid>()));
            var settings = new RunnerSettings
            {
                AgentId = 1,
                AgentName = "runner",
                ServerUrl = "https://pipelines.actions.githubusercontent.com/abcd",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
                .Returns(settings);

            if (_tokenSource != null)
            {
                _tokenSource.Dispose();
                _tokenSource = null;
            }

            _tokenSource = new CancellationTokenSource();
            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline = new Timeline(Guid.NewGuid());

            List<Pipelines.ActionStep> steps = new List<Pipelines.ActionStep>()
            {
                new Pipelines.ActionStep()
                {
                    Id = Guid.NewGuid(),
                    DisplayName = "action1",
                },
                new Pipelines.ActionStep()
                {
                    Id = Guid.NewGuid(),
                    DisplayName = "action2",
                },
                new Pipelines.ActionStep()
                {
                    Id = Guid.NewGuid(),
                    DisplayName = "action3",
                },
                new Pipelines.ActionStep()
                {
                    Id = Guid.NewGuid(),
                    DisplayName = "action4",
                },
                new Pipelines.ActionStep()
                {
                    Id = Guid.NewGuid(),
                    DisplayName = "action5",
                }
            };

            Guid jobId = Guid.NewGuid();
            _message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, "test", "test", null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), steps, null, null, null, null);
            GitHubContext github = new GitHubContext();
            github["repository"] = new Pipelines.ContextData.StringContextData("actions/runner");
            _message.ContextData.Add("github", github);

            hc.SetSingleton(_actionManager.Object);
            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_containerProvider.Object);
            hc.SetSingleton(_directoryManager.Object);
            hc.SetSingleton(_diagnosticLogManager.Object);
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // JobExecutionContext
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // Initial Job
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step1
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step2
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step3
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step4
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // step5
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // prepare1
            hc.EnqueueInstance<IPagingLogger>(_logger.Object); // prepare2

            hc.EnqueueInstance<IActionRunner>(step1);
            hc.EnqueueInstance<IActionRunner>(step2);
            hc.EnqueueInstance<IActionRunner>(step3);
            hc.EnqueueInstance<IActionRunner>(step4);
            hc.EnqueueInstance<IActionRunner>(step5);

            _jobEc.Initialize(hc);
            _jobEc.InitializeJob(_message, _tokenSource.Token);
            return hc;
        }

19 Source : JobRunnerL0.cs
with MIT License
from actions

private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _jobEc = new Runner.Worker.ExecutionContext();
            _config = new Mock<IConfigurationStore>();
            _extensions = new Mock<IExtensionManager>();
            _jobExtension = new Mock<IJobExtension>();
            _jobServer = new Mock<IJobServer>();
            _jobServerQueue = new Mock<IJobServerQueue>();
            _stepRunner = new Mock<IStepsRunner>();
            _logger = new Mock<IPagingLogger>();
            _temp = new Mock<ITempDirectoryManager>();
            _diagnosticLogManager = new Mock<IDiagnosticLogManager>();

            if (_tokenSource != null)
            {
                _tokenSource.Dispose();
                _tokenSource = null;
            }

            _tokenSource = new CancellationTokenSource();

            _jobRunner = new JobRunner();
            _jobRunner.Initialize(hc);

            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline = new Timeline(Guid.NewGuid());
            Guid jobId = Guid.NewGuid();
            _message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, testName, testName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
            _message.Variables[Constants.Variables.System.Culture] = "en-US";
            _message.Resources.Endpoints.Add(new ServiceEndpoint()
            {
                Name = WellKnownServiceEndpointNames.SystemVssConnection,
                Url = new Uri("https://pipelines.actions.githubusercontent.com"),
                Authorization = new EndpointAuthorization()
                {
                    Scheme = "Test",
                    Parameters = {
                        {"AccessToken", "token"}
                    }
                },

            });

            _message.Resources.Repositories.Add(new Pipelines.RepositoryResource()
            {
                Alias = Pipelines.PipelineConstants.SelfAlias,
                Id = "github",
                Version = "sha1"
            });
            _message.ContextData.Add("github", new Pipelines.ContextData.DictionaryContextData());

            _initResult.Clear();

            _jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.AgentJobRequestMessage>())).
                Returns(Task.FromResult(_initResult));

            var settings = new RunnerSettings
            {
                AgentId = 1,
                AgentName = "agent1",
                ServerUrl = "https://pipelines.actions.githubusercontent.com",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
                .Returns(settings);

            _logger.Setup(x => x.Setup(It.IsAny<Guid>(), It.IsAny<Guid>()));

            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServer.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_stepRunner.Object);
            hc.SetSingleton(_extensions.Object);
            hc.SetSingleton(_temp.Object);
            hc.SetSingleton(_diagnosticLogManager.Object);
            hc.EnqueueInstance<IExecutionContext>(_jobEc);
            hc.EnqueueInstance<IPagingLogger>(_logger.Object);
            hc.EnqueueInstance<IJobExtension>(_jobExtension.Object);
            return hc;
        }

19 Source : HostContextL0.cs
with MIT License
from actions

private void Teardown()
        {
            _hc?.Dispose();
            _tokenSource?.Dispose();
        }

19 Source : BackgroundTagging.cs
with GNU General Public License v3.0
from Acumatica

public void Dispose()
        {
            if (_isDisposed)
                return;

            _isDisposed = true;
            CancelTagging();
            _cancellationTokenSource.Dispose();
        }

19 Source : CodeMapWindowViewModel.cs
with GNU General Public License v3.0
from Acumatica

public override void FreeResources()
		{
			base.FreeResources();
			_cancellationTokenSource?.Dispose();

			if (Workspace != null)
			{
				Workspace.WorkspaceChanged -= OnWorkspaceChanged;
			}

			_dteEventsObserver.UnsubscribeEvents();
		}

19 Source : FileLoggerProcessor.cs
with MIT License
from adams85

public void Dispose()
        {
            lock (_logFiles)
                if (_status != Status.Completed)
                {
                    _completeTokenRegistration.Dispose();

                    _forcedCompleteTokenSource.Cancel();
                    _forcedCompleteTokenSource.Dispose();

                    _completeTaskCompletionSource.TrySetResult(null);

                    if (_fallbackFileAppender.IsValueCreated)
                        _fallbackFileAppender.Value.Dispose();

                    DisposeCore();

                    _status = Status.Completed;
                }
        }

19 Source : FileLoggerProcessor.cs
with MIT License
from adams85

private async Task ResetCoreAsync(Action onQueuesCompleted, bool complete)
        {
            CancellationTokenSource forcedCompleteTokenSource;
            Task[] completionTasks;

            lock (_logFiles)
            {
                if (_status != Status.Running)
                    return;

                forcedCompleteTokenSource = _forcedCompleteTokenSource;
                _forcedCompleteTokenSource = new CancellationTokenSource();

                completionTasks = _logFiles.Values.Select(async logFile =>
                {
                    logFile.Queue.Writer.Complete();

                    await logFile.WriteFileTask.ConfigureAwait(false);

                    if (logFile.IsOpen)
                        logFile.Close();
                }).ToArray();

                _logFiles.Clear();

                onQueuesCompleted?.Invoke();

                if (complete)
                    _status = Status.Completing;
            }

            try
            {
                var completionTimeoutTask = Task.Delay(Context.CompletionTimeout);
                if ((await Task.WhenAny(Task.WhenAll(completionTasks), completionTimeoutTask).ConfigureAwait(false)) == completionTimeoutTask)
                    Context.ReportDiagnosticEvent(new FileLoggerDiagnosticEvent.QueuesCompletionForced(this));

                forcedCompleteTokenSource.Cancel();
                forcedCompleteTokenSource.Dispose();
            }
            finally
            {
                if (complete)
                    Dispose();
            }
        }

19 Source : PlatformManager.cs
with GNU General Public License v3.0
from affederaffe

public void Dispose()
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
            SavePlatformInfosToFile();
        }

19 Source : PlatformSpawner.cs
with GNU General Public License v3.0
from affederaffe

public async Task ChangeToPlatformAsync(CustomPlatform platform)
        {
            if (platform == _platformManager.ActivePlatform) return;
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = _cancellationTokenSource.Token;

            DestroyCustomObjects();
            _platformManager.ActivePlatform.gameObject.SetActive(false);
            _platformManager.ActivePlatform = platform;

            if (platform.isDescriptor)
            {
                CustomPlatform? newPlatform = await _platformManager.CreatePlatformAsync(platform.fullPath);
                if (newPlatform is null)
                {
                    _ = ChangeToPlatformAsync(_platformManager.DefaultPlatform);
                    return;
                }
                
                _platformManager.AllPlatforms.Replace(platform, newPlatform);
                UnityEngine.Object.Destroy(platform.gameObject);
                if (cancellationToken.IsCancellationRequested) return;
                _platformManager.ActivePlatform = newPlatform;
            }

            _siraLog.Info($"Switching to {_platformManager.ActivePlatform.name}");
            _environmentHider.HideObjectsForPlatform(_platformManager.ActivePlatform);
            _platformManager.ActivePlatform.gameObject.SetActive(true);
            SpawnCustomObjects();
        }

19 Source : ConnectionManager.cs
with GNU General Public License v3.0
from affederaffe

public void Dispose()
        {
            _fileSystemWatcher.Changed -= OnFileChanged;
            _fileSystemWatcher.Created -= OnFileCreated;
            _fileSystemWatcher.Deleted -= OnFileDeleted;
            _fileSystemWatcher.Dispose();
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
            if (_isCinemaInstalled) DisposeCinemaConnection();
            if (_isSongCoreInstalled) DisposeSongCoreConnection();
        }

19 Source : StationProxy.cs
with Mozilla Public License 2.0
from agebullhu

public bool End()
        {
            if (RunTaskCancel == null)
                return false;
            RunTaskCancel.Cancel();
            _waitToken.Wait();
            RunTaskCancel.Dispose();
            RunTaskCancel = null;
            ZeroTrace.SystemLog($"{Config.StationName}(proxy)", "End");
            return true;
        }

19 Source : PollProxy.cs
with Mozilla Public License 2.0
from agebullhu

public bool End()
        {
            if (RunTaskCancel == null)
                return false;
            RunTaskCancel.Cancel();
            _waitToken.Wait();
            RunTaskCancel.Dispose();
            RunTaskCancel = null;
            ZeroTrace.SystemLog("ConnectionProxy", "End");
            return true;
        }

19 Source : Tester.cs
with Mozilla Public License 2.0
from agebullhu

void OnTestEnd()
        {
            if (Interlocked.Decrement(ref testerCount) == 0)
            {
                Cancel.Dispose();
                Cancel = null;
            }
        }

19 Source : RemoteRecorder.cs
with Mozilla Public License 2.0
from agebullhu

private bool Close()
        {
            if (Interlocked.CompareExchange(ref _state, StationState.Closing, StationState.Run) != StationState.Run)
                return true;
            RunTaskCancel.Dispose();
            RunTaskCancel = null;
            _waitToken.Wait();
            return true;
        }

19 Source : ZeroStation.cs
with Mozilla Public License 2.0
from agebullhu

private void OnStop()
        {
            State = StationState.Closing;
            OnRunStop();
            RunTaskCancel.Dispose();
            RunTaskCancel = null;
            State = StationState.Closed;
            ZeroApplication.OnObjectClose(this);
        }

19 Source : AutoCompleteModel.cs
with Apache License 2.0
from Aguafrommars

protected Task Filter()
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;

            return Task.Delay(200, token)
                    .ContinueWith(async task =>
                    {
                        if (task.IsCanceled)
                        {
                            return;
                        }
                        FilteredValues = await GetFilteredValues(CurrentValuereplacedtring, token)
                            .ConfigureAwait(false);
                       await JSRuntime.InvokeVoidAsync("bootstrapInteropt.showDropDownMenu", token, Id);
                       await InvokeAsync(StateHasChanged).ConfigureAwait(false);
                    }, TaskScheduler.Default);
        }

19 Source : EntitiesModel.cs
with Apache License 2.0
from Aguafrommars

protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    GridState.OnHeaderClicked -= GridState_OnHeaderClicked;
                    _cancellationTokenSource?.Dispose();
                }

                disposedValue = true;
            }
        }

19 Source : AutoCompleteModel.cs
with Apache License 2.0
from Aguafrommars

protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (!disposedValue)
            {
                if (disposing)
                {
                    _cancellationTokenSource?.Dispose();
                }

                disposedValue = true;
            }
        }

19 Source : EntitiesModel.cs
with Apache License 2.0
from Aguafrommars

protected Task OnFilterChanged(string filter)
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
                       
            return Task.Delay(500, token)
                .ContinueWith(async task =>
                {
                    _pageRequest.Filter = CreateRequestFilter(filter);

                    var page = await AdminStore.GetAsync(_pageRequest, token)
                                .ConfigureAwait(false);

                    if (task.IsCanceled)
                    {
                        return;
                    }

                    EnreplacedyList = page.Items;

                    await InvokeAsync(() => StateHasChanged())
                        .ConfigureAwait(false);
                }, TaskScheduler.Default);
        }

19 Source : TokenCleanerHost.cs
with Apache License 2.0
from Aguafrommars

protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _source?.Dispose();
                }
                disposedValue = true;
            }
        }

19 Source : RestClient.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            if (this._disposed)
                return;

            this._disposed = true;

            this.GlobalRateLimitEvent.Reset();

            if (this._bucketCleanerTokenSource?.IsCancellationRequested == false)
            {
                this._bucketCleanerTokenSource?.Cancel();
                this.Logger.LogDebug(LoggerEvents.RestCleaner, "Bucket cleaner task stopped.");
            }

            try
            {
                this._cleanerTask?.Dispose();
                this._bucketCleanerTokenSource?.Dispose();
                this.HttpClient?.Dispose();
            }
            catch { }

            this.RoutesToHashes.Clear();
            this.HashesToBuckets.Clear();
            this.RequestQueue.Clear();
        }

19 Source : SocketLock.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            try
            {
                this.TimeoutCancelSource?.Cancel();
                this.TimeoutCancelSource?.Dispose();
            }
            catch { }
        }

19 Source : WebSocketClient.cs
with MIT License
from Aiko-IT-Systems

public async Task DisconnectAsync(int code = 1000, string message = "")
        {
            // Ensure that messages cannot be sent
            await this._senderLock.WaitAsync().ConfigureAwait(false);

            try
            {
                this._isClientClose = true;
                if (this._ws != null && (this._ws.State == WebSocketState.Open || this._ws.State == WebSocketState.CloseReceived))
                    await this._ws.CloseOutputAsync((WebSocketCloseStatus)code, message, CancellationToken.None).ConfigureAwait(false);

                if (this._receiverTask != null)
                    await this._receiverTask.ConfigureAwait(false); // Ensure that receiving completed

                if (this._isConnected)
                    this._isConnected = false;

                if (!this._isDisposed)
                {
                    // Cancel all running tasks
                    if (this._socketToken.CanBeCanceled)
                        this._socketTokenSource?.Cancel();
                    this._socketTokenSource?.Dispose();

                    if (this._receiverToken.CanBeCanceled)
                        this._receiverTokenSource?.Cancel();
                    this._receiverTokenSource?.Dispose();

                    this._isDisposed = true;
                }
            }
            catch { }
            finally
            {
                this._senderLock.Release();
            }
        }

19 Source : WebSocketClient.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            if (this._isDisposed)
                return;

            this._isDisposed = true;

            this.DisconnectAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            this._receiverTokenSource?.Dispose();
            this._socketTokenSource?.Dispose();
        }

19 Source : ReactionCollector.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            GC.SuppressFinalize(this);
            this._ct.Dispose();
            this._tcs = null;
            this.message = null;
            this._collected?.Clear();
            this._collected = null;
        }

19 Source : PaginationRequest.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            this._ct.Dispose();
            this._tcs = null;
        }

19 Source : SocketLock.cs
with MIT License
from Aiko-IT-Systems

public void UnlockAfter(TimeSpan unlockDelay)
        {
            if (this.TimeoutCancelSource == null || this.LockSemapreplaced.CurrentCount > 0)
                return; // it's not unlockable because it's post-IDENTIFY or not locked

            try
            {
                this.TimeoutCancelSource.Cancel();
                this.TimeoutCancelSource.Dispose();
            }
            catch { }
            this.TimeoutCancelSource = null;

            this.UnlockTask = Task.Delay(unlockDelay, CancellationToken.None);
            _ = this.UnlockTask.ContinueWith(this.InternalUnlock);
        }

19 Source : WebSocketClient.cs
with MIT License
from Aiko-IT-Systems

public async Task ConnectAsync(Uri uri)
        {
            // Disconnect first
            try { await this.DisconnectAsync().ConfigureAwait(false); } catch { }

            // Disallow sending messages
            await this._senderLock.WaitAsync().ConfigureAwait(false);

            try
            {
                // This can be null at this point
                this._receiverTokenSource?.Dispose();
                this._socketTokenSource?.Dispose();

                this._ws?.Dispose();
                this._ws = new ClientWebSocket();
                this._ws.Options.Proxy = this.Proxy;
                this._ws.Options.KeepAliveInterval = TimeSpan.Zero;
                if (this._defaultHeaders != null)
                    foreach (var (k, v) in this._defaultHeaders)
                        this._ws.Options.SetRequestHeader(k, v);

                this._receiverTokenSource = new CancellationTokenSource();
                this._receiverToken = this._receiverTokenSource.Token;

                this._socketTokenSource = new CancellationTokenSource();
                this._socketToken = this._socketTokenSource.Token;

                this._isClientClose = false;
                this._isDisposed = false;
                await this._ws.ConnectAsync(uri, this._socketToken).ConfigureAwait(false);
                this._receiverTask = Task.Run(this.ReceiverLoopAsync, this._receiverToken);
            }
            finally
            {
                this._senderLock.Release();
            }
        }

19 Source : InteractionPaginationRequest.cs
with MIT License
from Aiko-IT-Systems

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

19 Source : CollectRequest.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            this._ct.Dispose();
            this._tcs = null;
            this._predicate = null;

            if (this._collected != null)
            {
                this._collected.Clear();
                this._collected = null;
            }
        }

19 Source : MatchRequest.cs
with MIT License
from Aiko-IT-Systems

public void Dispose()
        {
            this._ct.Dispose();
            this._tcs = null;
            this._predicate = null;
        }

19 Source : SubstrateClient.cs
with Apache License 2.0
from ajuna-network

protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    new JoinableTaskFactory(new JoinableTaskContext()).Run(CloseAsync);
                    _connectTokenSource?.Dispose();

                    // dispose remaining request tokens
                    foreach (var key in _requestTokenSourceDict.Keys) key?.Dispose();
                    _requestTokenSourceDict.Clear();

                    _jsonRpc?.Dispose();
                    _socket?.Dispose();
                    Logger.Debug("Client disposed.");
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                _disposedValue = true;
            }
        }

19 Source : SubstrateClient.cs
with Apache License 2.0
from ajuna-network

public async Task ConnectAsync(CancellationToken token)
        {
            if (_socket != null && _socket.State == WebSocketState.Open)
                return;

            if (_socket == null || _socket.State != WebSocketState.None)
            {
                _jsonRpc?.Dispose();
                _socket?.Dispose();
                _socket = new ClientWebSocket();
            }

            _connectTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, _connectTokenSource.Token);
            await _socket.ConnectAsync(_uri, linkedTokenSource.Token);
            linkedTokenSource.Dispose();
            _connectTokenSource.Dispose();
            _connectTokenSource = null;
            Logger.Debug("Connected to Websocket.");

            var formatter = new JsonMessageFormatter();
            // adding convertersto the formatter
            formatter.JsonSerializer.Converters.Add(new GenericTypeConverter<U8>());
            formatter.JsonSerializer.Converters.Add(new GenericTypeConverter<U16>());
            formatter.JsonSerializer.Converters.Add(new GenericTypeConverter<U32>());
            formatter.JsonSerializer.Converters.Add(new GenericTypeConverter<U64>());
            formatter.JsonSerializer.Converters.Add(new GenericTypeConverter<Hash>());
            formatter.JsonSerializer.Converters.Add(_extrinsicJsonConverter);
            formatter.JsonSerializer.Converters.Add(_extrinsicStatusJsonConverter);

            _jsonRpc = new JsonRpc(new WebSocketMessageHandler(_socket, formatter));
            _jsonRpc.TraceSource.Listeners.Add(new NLogTraceListener());
            _jsonRpc.TraceSource.Switch.Level = SourceLevels.Warning;
            _jsonRpc.AddLocalRpcTarget(Listener, new JsonRpcTargetOptions {AllowNonPublicInvocation = false});
            _jsonRpc.StartListening();
            Logger.Debug("Listening to websocket.");

            var result = await State.GetMetaDataAsync(token);
            var metaDataParser = new MetaDataParser(_uri.OriginalString, result);
            MetaData = metaDataParser.MetaData;
            Logger.Debug("MetaData parsed.");

            var genesis = new BlockNumber();
            genesis.Create(0);
            GenesisHash = await Chain.GetBlockHashAsync(genesis, token);
            Logger.Debug("Genesis hash parsed.");

            RuntimeVersion = await State.GetRuntimeVersionAsync(token);
            Logger.Debug("Runtime version parsed.");

            _jsonRpc.TraceSource.Switch.Level = SourceLevels.All;
        }

19 Source : SubstrateClient.cs
with Apache License 2.0
from ajuna-network

internal async Task<T> InvokeAsync<T>(string method, object parameters, CancellationToken token)
        {
            if (_socket?.State != WebSocketState.Open)
                throw new ClientNotConnectedException($"WebSocketState is not open! Currently {_socket?.State}!");

            Logger.Debug($"Invoking request[{method}, params: {parameters}] {MetaData?.Origin}");

            var requestTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            _requestTokenSourceDict.TryAdd(requestTokenSource, string.Empty);

            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, requestTokenSource.Token);
            var resultString =
                await _jsonRpc.InvokeWithParameterObjectAsync<T>(method, parameters, linkedTokenSource.Token);

            linkedTokenSource.Dispose();
            requestTokenSource.Dispose();

            _requestTokenSourceDict.TryRemove(requestTokenSource, out var _);

            return resultString;
        }

19 Source : FlowableFromTask.cs
with Apache License 2.0
from akarnokd

public override void Cancel()
            {
                base.Cancel();
                cts.Dispose();
            }

19 Source : TaskExecutorService.cs
with Apache License 2.0
from akarnokd

public void Dispose()
                {
                    cts.Dispose();
                    parent.tasks.Delete(this);
                }

19 Source : ProviderTests.cs
with MIT License
from Akinzekeel

[TestMethod]
        public async Task CancellationTokenSourceDisposedException_Is_Handled()
        {
            ProviderDelegate<object> provider = (r, _) =>
            {
                return ValueTask.FromResult(new BlazorGridResult<object>
                {
                    Data = new List<object> { },
                    TotalCount = 0
                });
            };

            var grid = RenderComponent<BlazorGrid<object>>(
                Parameter(nameof(BlazorGrid<object>.Provider), provider),
                Template<object>(nameof(ChildContent), context => b =>
                {
                    b.OpenComponent<StaticGridCol>(0);
                    b.AddAttribute(1, nameof(StaticGridCol.Caption), "test");
                    b.CloseComponent();
                })
            );

            // Change the provider to throw an exception
            provider = (r, _) =>
            {
                var ct = new CancellationTokenSource();
                var token = ct.Token;
                ct.Dispose();
                ct.Cancel();

                return ValueTask.FromResult(new BlazorGridResult<object>
                {
                    Data = new List<object> { },
                    TotalCount = 0
                });
            };

            grid.SetParametersAndRender(
                Parameter(nameof(BlazorGrid<object>.Provider), provider)
            );

            await grid.InvokeAsync(() => grid.Instance.ReloadAsync());

            // replacedert that there is no error overlay
            var overlays = grid.FindAll(".grid-overlay");
            replacedert.AreEqual(0, overlays.Count, overlays.Select(x => x.InnerHtml).FirstOrDefault());
        }

See More Examples