System.Threading.CancellationTokenSource.Cancel()

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

4152 Examples 7

19 View Source File : MainForm.cs
License : MIT License
Project Creator : 13xforever

private void DumpDisc(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var backgroundWorker = (BackgroundWorker)sender;
            var dumper = (Dumper)doWorkEventArgs.Argument;
            try
            {
                var threadCts = new CancellationTokenSource();
                var combinedToken = CancellationTokenSource.CreateLinkedTokenSource(threadCts.Token, dumper.Cts.Token);
                var monitor = new Thread(() =>
                                         {
                                             try
                                             {
                                                 do
                                                 {
                                                     if (dumper.TotalSectors > 0 && backgroundWorker.IsBusy && !backgroundWorker.CancellationPending)
                                                        try { backgroundWorker.ReportProgress((int)(dumper.CurrentSector * 10000L / dumper.TotalSectors), dumper); } catch { }
                                                     Task.Delay(1000, combinedToken.Token).GetAwaiter().GetResult();
                                                 } while (!combinedToken.Token.IsCancellationRequested);
                                             }
                                             catch (TaskCanceledException)
                                             {
                                             }
                                         });
                monitor.Start();
                dumper.DumpAsync(settings.OutputDir).Wait(dumper.Cts.Token);
                threadCts.Cancel();
                monitor.Join(100);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Disc dumping error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            doWorkEventArgs.Result = dumper;
        }

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

public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout, string message = "The operation has timed out.")
        {
            using (var timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
                if (completedTask == task)
                {
                    timeoutCancellationTokenSource.Cancel();
                    return await task;
                }
                else
                {
                    throw new TimeoutException(message);
                }
            }
        }

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

public static async Task TimeoutAfter(this Task task, TimeSpan timeout, string message = "The operation has timed out.")
        {
            using (var timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
                if (completedTask == task)
                {
                    timeoutCancellationTokenSource.Cancel();
                    await task;
                }
                else
                {
                    throw new TimeoutException(message);
                }
            }
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : 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 View Source File : RecordStream.cs
License : MIT License
Project Creator : 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 View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott

public void Cancel() => this.cts.Cancel();

19 View Source File : SimProc.cs
License : MIT License
Project Creator : abdullin

public void Cancel() {
            // issues a soft cancel token
            _cts.Cancel();
        }

19 View Source File : TaskHelpers.cs
License : MIT License
Project Creator : abdullin

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

19 View Source File : TaskHelpers.cs
License : MIT License
Project Creator : abdullin

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

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static async Task SearchForFoldersAsync(string rootPath)
        {
            if (searchForFoldersToken != null)
            {
                searchForFoldersToken.Cancel();
            }

            searchForFoldersToken = new CancellationTokenSource();
            await Task.Run(() => SearchForFolders(rootPath, searchForFoldersToken.Token), searchForFoldersToken.Token);
            searchForFoldersToken = null;
        }

19 View Source File : AudioDeviceHandler.cs
License : MIT License
Project Creator : ABTSoftware

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

        }

19 View Source File : UpgradeService.cs
License : MIT License
Project Creator : Accelerider

void IUpgradeService.Stop()
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource = null;
        }

19 View Source File : PrimitiveMethods.Download.cs
License : MIT License
Project Creator : Accelerider

public static IObservable<(long Offset, int Bytes)> CreateBlockDownloadItem(
            Func<Task<(HttpWebResponse response, Stream inputStream)>> streamPairFactory,
            BlockTransferContext context) => Observable.Create<(long Offset, int Bytes)>(o =>
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            // Execute copy stream by async.
            Task.Run(async () =>
            {
                try
                {
                    (HttpWebResponse response, Stream outputStream) = await streamPairFactory();

                    using (response)
                    using (var inputStream = response.GetResponseStream())
                    using (outputStream)
                    {
                        byte[] buffer = new byte[128 * 1024];
                        int count;

                        Guards.ThrowIfNull(inputStream);

                        // ReSharper disable once PossibleNullReferenceException
                        while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                Debug.WriteLine($"[CANCELLED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                                o.OnError(new BlockTransferException(context, new OperationCanceledException()));
                                return;
                            }

                            outputStream.Write(buffer, 0, count);
                            o.OnNext((context.Offset, count));
                        }
                    }

                    o.OnCompleted();
                }
                catch (Exception e)
                {
                    o.OnError(new BlockTransferException(context, e));
                }
            }, cancellationToken);

            return () =>
            {
                Debug.WriteLine($"[DISPOSED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                cancellationTokenSource.Cancel();
            };
        });

19 View Source File : FileDownloader.cs
License : MIT License
Project Creator : Accelerider

public void Stop()
        {
            ThrowIfDisposed();

            switch (Status)
            {
                case TransferStatus.Ready:
                    _cancellationTokenSource?.Cancel();
                    return;
                case TransferStatus.Transferring:
                    Dispose(true);
                    Status = TransferStatus.Suspended;
                    break;
            }
        }

19 View Source File : FileDownloader.cs
License : MIT License
Project Creator : Accelerider

protected virtual void Dispose(bool disposing)
        {
            if (Status == TransferStatus.Disposed) return;

            if (disposing)
            {
                _cancellationTokenSource?.Cancel();
                _disposable?.Dispose();
            }
        }

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

public void ShutdownRunner(ShutdownReason reason)
        {
            ArgUtil.NotNull(reason, nameof(reason));
            _trace.Info($"Runner will be shutdown for {reason.ToString()}");
            RunnerShutdownReason = reason;
            _runnerShutdownTokenSource.Cancel();
        }

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

public static void DeleteDirectory(string path, bool contentsOnly, bool continueOnContentDeleteError, CancellationToken cancellationToken)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            DirectoryInfo directory = new DirectoryInfo(path);
            if (!directory.Exists)
            {
                return;
            }

            if (!contentsOnly)
            {
                // Remove the readonly flag.
                RemoveReadOnly(directory);

                // Check if the directory is a reparse point.
                if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                {
                    // Delete the reparse point directory and short-circuit.
                    directory.Delete();
                    return;
                }
            }

            // Initialize a concurrent stack to store the directories. The directories
            // cannot be deleted until the files are deleted.
            var directories = new ConcurrentStack<DirectoryInfo>();

            if (!contentsOnly)
            {
                directories.Push(directory);
            }

            // Create a new token source for the parallel query. The parallel query should be
            // canceled after the first error is encountered. Otherwise the number of exceptions
            // could get out of control for a large directory with access denied on every file.
            using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                try
                {
                    // Recursively delete all files and store all subdirectories.
                    Enumerate(directory, tokenSource)
                        .AsParallel()
                        .WithCancellation(tokenSource.Token)
                        .ForAll((FileSystemInfo item) =>
                        {
                            bool success = false;
                            try
                            {
                                // Remove the readonly attribute.
                                RemoveReadOnly(item);

                                // Check if the item is a file.
                                if (item is FileInfo)
                                {
                                    // Delete the file.
                                    item.Delete();
                                }
                                else
                                {
                                    // Check if the item is a directory reparse point.
                                    var subdirectory = item as DirectoryInfo;
                                    ArgUtil.NotNull(subdirectory, nameof(subdirectory));
                                    if (subdirectory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                                    {
                                        try
                                        {
                                            // Delete the reparse point.
                                            subdirectory.Delete();
                                        }
                                        catch (DirectoryNotFoundException)
                                        {
                                            // The target of the reparse point directory has been deleted.
                                            // Therefore the item is no longer a directory and is now a file.
                                            //
                                            // Deletion of reparse point directories happens in parallel. This case can occur
                                            // when reparse point directory FOO points to some other reparse point directory BAR,
                                            // and BAR is deleted after the DirectoryInfo for FOO has already been initialized.
                                            File.Delete(subdirectory.FullName);
                                        }
                                    }
                                    else
                                    {
                                        // Store the directory.
                                        directories.Push(subdirectory);
                                    }
                                }

                                success = true;
                            }
                            catch (Exception) when (continueOnContentDeleteError)
                            {
                                // ignore any exception when continueOnContentDeleteError is true.
                                success = true;
                            }
                            finally
                            {
                                if (!success)
                                {
                                    tokenSource.Cancel(); // Cancel is thread-safe.
                                }
                            }
                        });
                }
                catch (Exception)
                {
                    tokenSource.Cancel();
                    throw;
                }
            }

            // Delete the directories.
            foreach (DirectoryInfo dir in directories.OrderByDescending(x => x.FullName.Length))
            {
                cancellationToken.ThrowIfCancellationRequested();
                dir.Delete();
            }
        }

19 View Source File : Runner.cs
License : MIT License
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : actions

private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            e.Cancel = true;
            tokenSource.Cancel();
        }

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

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

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

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

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

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

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

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

public void CancelToken()
        {
            try
            {
                _cancellationTokenSource.Cancel();
            }
            catch (ObjectDisposedException e)
            {
                Trace.Info($"Attempted to cancel a disposed token, the execution is already complete: {e.ToString()}");
            }
        }

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

public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
        {
            Trace.Entering();
            ArgUtil.NotNull(jobContext, nameof(jobContext));

            // create a new timeline record node for 'Finalize job'
            IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null, ActionRunStage.Post);
            using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
            {
                try
                {
                    context.Start();
                    context.Debug("Starting: Complete job");

                    Trace.Info("Initialize Env context");

#if OS_WINDOWS
                    var envContext = new DictionaryContextData();
#else
                    var envContext = new CaseSensitiveDictionaryContextData();
#endif
                    context.ExpressionValues["env"] = envContext;
                    foreach (var pair in context.Global.EnvironmentVariables)
                    {
                        envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
                    }

                    // Populate env context for each step
                    Trace.Info("Initialize steps context");
                    context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);

                    var templateEvaluator = context.ToPipelineTemplateEvaluator();
                    // Evaluate job outputs
                    if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set job outputs");

                            // Populate env context for each step
                            Trace.Info("Initialize Env context for evaluating job outputs");

                            var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
                            foreach (var output in outputs)
                            {
                                if (string.IsNullOrEmpty(output.Value))
                                {
                                    context.Debug($"Skip output '{output.Key}' since it's empty");
                                    continue;
                                }

                                if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
                                {
                                    context.Warning($"Skip output '{output.Key}' since it may contain secret.");
                                    continue;
                                }

                                context.Output($"Set output '{output.Key}'");
                                jobContext.JobOutputs[output.Key] = output.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Fail to evaluate job outputs");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    // Evaluate environment data
                    if (jobContext.ActionsEnvironment?.Url != null && jobContext.ActionsEnvironment?.Url.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set environment url");

                            var environmentUrlToken = templateEvaluator.EvaluateEnvironmentUrl(jobContext.ActionsEnvironment.Url, context.ExpressionValues, context.ExpressionFunctions);
                            var environmentUrl = environmentUrlToken.replacedertString("environment.url");
                            if (!string.Equals(environmentUrl.Value, HostContext.SecretMasker.MaskSecrets(environmentUrl.Value)))
                            {
                                context.Warning($"Skip setting environment url as environment '{jobContext.ActionsEnvironment.Name}' may contain secret.");
                            }
                            else
                            {
                                context.Output($"Evaluated environment url: {environmentUrl}");
                                jobContext.ActionsEnvironment.Url = environmentUrlToken;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Failed to evaluate environment url");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
                    {
                        Trace.Info("Support log upload starting.");
                        context.Output("Uploading runner diagnostic logs");

                        IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();

                        try
                        {
                            diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);

                            Trace.Info("Support log upload complete.");
                            context.Output("Completed runner diagnostic log upload");
                        }
                        catch (Exception ex)
                        {
                            // Log the error but make sure we continue gracefully.
                            Trace.Info("Error uploading support logs.");
                            context.Output("Error uploading runner diagnostic logs");
                            Trace.Error(ex);
                        }
                    }

                    if (_processCleanup)
                    {
                        context.Output("Cleaning up orphan processes");

                        // Only check environment variable for any process that doesn't run before we invoke our process.
                        Dictionary<int, Process> currentProcesses = SnapshotProcesses();
                        foreach (var proc in currentProcesses)
                        {
                            if (proc.Key == Process.GetCurrentProcess().Id)
                            {
                                // skip for current process.
                                continue;
                            }

                            if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
                            {
                                Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
                            }
                            else
                            {
                                Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");

                                string lookupId = null;
                                try
                                {
                                    lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
                                    Trace.Verbose(ex.ToString());
                                }

                                if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
                                {
                                    context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
                                    try
                                    {
                                        proc.Value.Kill();
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.Error("Catch exception during orphan process cleanup.");
                                        Trace.Error(ex);
                                    }
                                }
                            }
                        }
                    }

                    if (_diskSpaceCheckTask != null)
                    {
                        _diskSpaceCheckToken.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    // Log and ignore the error from JobExtension finalization.
                    Trace.Error($"Caught exception from JobExtension finalization: {ex}");
                    context.Output(ex.Message);
                }
                finally
                {
                    context.Debug("Finishing: Complete job");
                    context.Complete();
                }
            }
        }

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

public async Task<int> RunAsync(string pipeIn, string pipeOut)
        {
            try
            {
                // Setup way to handle SIGTERM/unloading signals
                _completedCommand.Reset();
                HostContext.Unloading += Worker_Unloading;

                // Validate args.
                ArgUtil.NotNullOrEmpty(pipeIn, nameof(pipeIn));
                ArgUtil.NotNullOrEmpty(pipeOut, nameof(pipeOut));
                VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);
                var jobRunner = HostContext.CreateService<IJobRunner>();

                using (var channel = HostContext.CreateService<IProcessChannel>())
                using (var jobRequestCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(HostContext.RunnerShutdownToken))
                using (var channelTokenSource = new CancellationTokenSource())
                {
                    // Start the channel.
                    channel.StartClient(pipeIn, pipeOut);

                    // Wait for up to 30 seconds for a message from the channel.
                    HostContext.WritePerfCounter("WorkerWaitingForJobMessage");
                    Trace.Info("Waiting to receive the job message from the channel.");
                    WorkerMessage channelMessage;
                    using (var csChannelMessage = new CancellationTokenSource(_workerStartTimeout))
                    {
                        channelMessage = await channel.ReceiveAsync(csChannelMessage.Token);
                    }

                    // Deserialize the job message.
                    Trace.Info("Message received.");
                    ArgUtil.Equal(MessageType.NewJobRequest, channelMessage.MessageType, nameof(channelMessage.MessageType));
                    ArgUtil.NotNullOrEmpty(channelMessage.Body, nameof(channelMessage.Body));
                    var jobMessage = StringUtil.ConvertFromJson<Pipelines.AgentJobRequestMessage>(channelMessage.Body);
                    ArgUtil.NotNull(jobMessage, nameof(jobMessage));
                    HostContext.WritePerfCounter($"WorkerJobMessageReceived_{jobMessage.RequestId.ToString()}");

                    // Initialize the secret masker and set the thread culture.
                    InitializeSecretMasker(jobMessage);
                    SetCulture(jobMessage);

                    // Start the job.
                    Trace.Info($"Job message:{Environment.NewLine} {StringUtil.ConvertToJson(jobMessage)}");
                    Task<TaskResult> jobRunnerTask = jobRunner.RunAsync(jobMessage, jobRequestCancellationToken.Token);

                    // Start listening for a cancel message from the channel.
                    Trace.Info("Listening for cancel message from the channel.");
                    Task<WorkerMessage> channelTask = channel.ReceiveAsync(channelTokenSource.Token);

                    // Wait for one of the tasks to complete.
                    Trace.Info("Waiting for the job to complete or for a cancel message from the channel.");
                    Task.WaitAny(jobRunnerTask, channelTask);
                    // Handle if the job completed.
                    if (jobRunnerTask.IsCompleted)
                    {
                        Trace.Info("Job completed.");
                        channelTokenSource.Cancel(); // Cancel waiting for a message from the channel.
                        return TaskResultUtil.TranslateToReturnCode(await jobRunnerTask);
                    }

                    // Otherwise a cancel message was received from the channel.
                    Trace.Info("Cancellation/Shutdown message received.");
                    channelMessage = await channelTask;
                    switch (channelMessage.MessageType)
                    {
                        case MessageType.CancelRequest:
                            jobRequestCancellationToken.Cancel();   // Expire the host cancellation token.
                            break;
                        case MessageType.RunnerShutdown:
                            HostContext.ShutdownRunner(ShutdownReason.UserCancelled);
                            break;
                        case MessageType.OperatingSystemShutdown:
                            HostContext.ShutdownRunner(ShutdownReason.OperatingSystemShutdown);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException(nameof(channelMessage.MessageType), channelMessage.MessageType, nameof(channelMessage.MessageType));
                    }

                    // Await the job.
                    return TaskResultUtil.TranslateToReturnCode(await jobRunnerTask);
                }
            }
            finally
            {
                HostContext.Unloading -= Worker_Unloading;
                _completedCommand.Set();
            }
        }

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

public void ShutdownRunner(ShutdownReason reason)
        {
            ArgUtil.NotNull(reason, nameof(reason));
            RunnerShutdownReason = reason;
            _runnerShutdownTokenSource.Cancel();
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void DispatcherRenewJobRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequest));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
                _runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count == 5)
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else
                                {
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);

                replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully);
                _runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void RenewJobRequestNewAgentNameUpdatesSettings()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var count = 0;
                var oldName = "OldName";
                var newName = "NewName";
                var oldSettings = new RunnerSettings { AgentName = oldName };
                var reservedAgent = new TaskAgentReference { Name = newName };

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                var request = new Mock<TaskAgentJobRequest>();
                request.Object.ReservedAgent = reservedAgent;
                PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
                _runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request.Object);
                                }
                                else if (count == 5 || count == 6 || count == 7)
                                {
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request.Object);
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                // Act
                await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);

                // replacedert
                _configurationStore.Verify(x => x.SaveSettings(It.Is<RunnerSettings>(settings => settings.AgentName == newName)), Times.Once);
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void RenewJobRequestSameAgentNameIgnored()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var count = 0;
                var oldName = "OldName";
                var newName = "OldName";
                var oldSettings = new RunnerSettings { AgentName = oldName };
                var reservedAgent = new TaskAgentReference { Name = newName };

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                var request = new Mock<TaskAgentJobRequest>();
                request.Object.ReservedAgent = reservedAgent;
                PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
                _runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request.Object);
                                }
                                else if (count == 5 || count == 6 || count == 7)
                                {
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request.Object);
                                }
                            });
                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                // Act
                await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);

                // replacedert
                _configurationStore.Verify(x => x.SaveSettings(It.IsAny<RunnerSettings>()), Times.Never);
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void RenewJobRequestNullAgentNameIgnored()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var count = 0;
                var oldName = "OldName";
                var oldSettings = new RunnerSettings { AgentName = oldName };

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                var request = new Mock<TaskAgentJobRequest>();
                PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
                _runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request.Object);
                                }
                                else if (count == 5 || count == 6 || count == 7)
                                {
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request.Object);
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                // Act
                await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);

                // replacedert
                _configurationStore.Verify(x => x.SaveSettings(It.IsAny<RunnerSettings>()), Times.Never);
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void DispatcherRenewJobRequestRecoverFromExceptions()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestRecoverFromExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
                _runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count == 5 || count == 6 || count == 7)
                                {
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);

                replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                replacedert.True(cancellationTokenSource.IsCancellationRequested);
                _runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(8));
                _runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
                _runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Once);
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public async Task JobExtensionInitializeCancelled()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                _jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.AgentJobRequestMessage>()))
                    .Throws(new OperationCanceledException());
                _tokenSource.Cancel();

                await _jobRunner.RunAsync(_message, _tokenSource.Token);

                replacedert.Equal(TaskResult.Canceled, _jobEc.Result);
                _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>()), Times.Never);
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Worker")]
        public async void DispatchRunNewJob()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                var worker = new GitHub.Runner.Worker.Worker();
                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance<IJobRunner>(_jobRunner.Object);
                worker.Initialize(hc);
                var jobMessage = CreateJobRequestMessage("job1");
                var arWorkerMessages = new WorkerMessage[]
                    {
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(jobMessage),
                            MessageType = MessageType.NewJobRequest
                        }
                    };
                var workerMessages = new Queue<WorkerMessage>(arWorkerMessages);

                _processChannel
                    .Setup(x => x.ReceiveAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                    {
                        // Return the job message.
                        if (workerMessages.Count > 0)
                        {
                            return workerMessages.Dequeue();
                        }

                        // Wait for the text to run
                        await Task.Delay(-1, tokenSource.Token);
                        return default(WorkerMessage);
                    });
                _jobRunner.Setup(x => x.RunAsync(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<TaskResult>(TaskResult.Succeeded));

                //Act
                await worker.RunAsync(pipeIn: "1", pipeOut: "2");

                //replacedert
                _processChannel.Verify(x => x.StartClient("1", "2"), Times.Once());
                _jobRunner.Verify(x => x.RunAsync(
                    It.Is<Pipelines.AgentJobRequestMessage>(y => IsMessageIdentical(y, jobMessage)), It.IsAny<CancellationToken>()));
                tokenSource.Cancel();
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task TestCancel()
        {
            const int SecondsToRun = 20;
            using (TestHostContext hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                Tracing trace = hc.GetTrace();
                var processInvoker = new ProcessInvokerWrapper();
                processInvoker.Initialize(hc);
                Stopwatch watch = Stopwatch.StartNew();
                Task execTask;
#if OS_WINDOWS
                execTask = processInvoker.ExecuteAsync("", "cmd.exe", $"/c \"choice /T {SecondsToRun} /D y\"", null, tokenSource.Token);
#else
                execTask = processInvoker.ExecuteAsync("", "bash", $"-c \"sleep {SecondsToRun}s\"", null, tokenSource.Token);
#endif
                await Task.Delay(500);
                tokenSource.Cancel();
                try
                {
                    await execTask;
                }
                catch (OperationCanceledException)
                {
                    trace.Info("Get expected OperationCanceledException.");
                }

                replacedert.True(execTask.IsCompleted);
                replacedert.True(!execTask.IsFaulted);
                replacedert.True(execTask.IsCanceled);
                watch.Stop();
                long elapsedSeconds = watch.ElapsedMilliseconds / 1000;

#if ARM
                // if cancellation fails, then execution time is more than 15 seconds
                // longer time to compensate for a slower ARM environment (e.g. Raspberry Pi)
                long expectedSeconds = (SecondsToRun * 3) / 4;
#else
                // if cancellation fails, then execution time is more than 10 seconds
                long expectedSeconds = SecondsToRun / 2;
#endif

                replacedert.True(elapsedSeconds <= expectedSeconds, $"cancellation failed, because task took too long to run. {elapsedSeconds}");
            }
        }

19 View Source File : BackgroundTagging.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public void CancelTagging()
        {
            if (!IsTaskRunning() || CancellationToken.IsCancellationRequested)
                return;

            _cancellationTokenSource.Cancel();
        }

19 View Source File : CodeMapWindowViewModel.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void ClearCodeMap()
		{
			_cancellationTokenSource?.Cancel();
			Tree?.Clear();
			Tree = null;
		}

19 View Source File : VideoSource.cs
License : MIT License
Project Creator : adamfisher

public virtual Task<bool> Cancel()
        {
            if (!IsLoading)
                return Task.FromResult(false);

            var completionSource1 = new TaskCompletionSource<bool>();
            var completionSource2 = Interlocked.CompareExchange(ref _completionSource, completionSource1, null);

            if (completionSource2 == null)
                _cancellationTokenSource.Cancel();
            else
                completionSource1 = completionSource2;

            return completionSource1.Task;
        }

19 View Source File : FileLoggerProcessor.cs
License : MIT License
Project Creator : 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 View Source File : FileLoggerProcessor.cs
License : MIT License
Project Creator : 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 View Source File : SettingsTest.cs
License : MIT License
Project Creator : adams85

[Fact]
        public async Task ReloadOptionsSettings()
        {
            var configJson =
[email protected]"{{
    ""{FileLoggerProvider.Alias}"": {{
        ""{nameof(FileLoggerOptions.IncludeScopes)}"" : true,
        ""{nameof(FileLoggerOptions.Files)}"": [
        {{
            ""{nameof(LogFileOptions.Path)}"": ""test.log"",
        }}],
        ""{nameof(LoggerFilterRule.LogLevel)}"": {{ 
            ""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.Trace}"" 
        }}
    }}
}}";

            var fileProvider = new MemoryFileProvider();
            fileProvider.CreateFile("config.json", configJson, Encoding.UTF8);

            var cb = new ConfigurationBuilder();
            cb.AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: true);
            IConfigurationRoot config = cb.Build();

            var completeCts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(completeCts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b =>
            {
                b.AddConfiguration(config);
                b.AddFile(context);
            });

            var fileAppender = new MemoryFileAppender(fileProvider);
            services.Configure<FileLoggerOptions>(o => o.FileAppender ??= fileAppender);

            FileLoggerProvider[] providers;

            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                providers = context.GetProviders(sp).ToArray();
                replacedert.Equal(1, providers.Length);

                var resetTasks = new List<Task>();
                foreach (FileLoggerProvider provider in providers)
                    provider.Reset += (s, e) => resetTasks.Add(e);

                ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
                ILogger<SettingsTest> logger1 = loggerFactory.CreateLogger<SettingsTest>();

                using (logger1.BeginScope("SCOPE"))
                {
                    logger1.LogTrace("This is a nice logger.");

                    using (logger1.BeginScope("NESTED SCOPE"))
                    {
                        logger1.LogInformation("This is a smart logger.");

                        // changing switch and scopes inclusion
                        configJson =
[email protected]"{{
    ""{FileLoggerProvider.Alias}"": {{
        ""{nameof(FileLoggerOptions.Files)}"": [
        {{
            ""{nameof(LogFileOptions.Path)}"": ""test.log"",
        }}],
        ""{nameof(LoggerFilterRule.LogLevel)}"": {{ 
            ""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.Information}"" 
        }}
    }}
}}";

                        replacedert.Equal(0, resetTasks.Count);
                        fileProvider.WriteContent("config.json", configJson);

                        // reload is triggered twice due to a bug in the framework (https://github.com/aspnet/Logging/issues/874)
                        replacedert.Equal(1 * 2, resetTasks.Count);

                        // ensuring that reset has been finished and the new settings are effective
                        await Task.WhenAll(resetTasks);

                        logger1 = loggerFactory.CreateLogger<SettingsTest>();

                        logger1.LogInformation("This one shouldn't include scopes.");
                        logger1.LogTrace("This one shouldn't be included at all.");
                    }
                }

                completeCts.Cancel();

                // ensuring that all entries are processed
                await context.GetCompletion(sp);
                replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
            }

            var logFile = (MemoryFileInfo)fileProvider.GetFileInfo("test.log");
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"trce: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      => SCOPE",
                $"      This is a nice logger.",
                $"info: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      => SCOPE => NESTED SCOPE",
                $"      This is a smart logger.",
                $"info: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This one shouldn't include scopes.",
                ""
            }, lines);
        }

19 View Source File : EdgeCasesTest.cs
License : MIT License
Project Creator : adams85

[Fact]
        public async Task FailingEntryDontGetStuck()
        {
            var logsDirName = Guid.NewGuid().ToString("D");

            var tempPath = Path.Combine(Path.GetTempPath());
            var logPath = Path.Combine(tempPath, logsDirName);

            if (Directory.Exists(logPath))
                Directory.Delete(logPath, recursive: true);

            var fileProvider = new PhysicalFileProvider(tempPath);

            var options = new FileLoggerOptions
            {
                FileAppender = new PhysicalFileAppender(fileProvider),
                BasePath = logsDirName,
                Files = new[]
                {
                    new LogFileOptions
                    {
                        Path = "default.log",
                    },
                },
            };
            var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);

            var completeCts = new CancellationTokenSource();
            var completionTimeoutMs = 2000;
            var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context));
            services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);

            string filePath = Path.Combine(logPath, "default.log");

            try
            {
                FileLoggerProvider[] providers;

                using (ServiceProvider sp = services.BuildServiceProvider())
                {
                    providers = context.GetProviders(sp).ToArray();
                    replacedert.Equal(1, providers.Length);

                    var resetTasks = new List<Task>();
                    foreach (FileLoggerProvider provider in providers)
                        provider.Reset += (s, e) => resetTasks.Add(e);

                    ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                    ILogger logger = loggerFactory.CreateLogger("X");

                    logger.LogInformation("This should get through.");

                    optionsMonitor.Reload();
                    // ensuring that reset has been finished and the new settings are effective
                    await Task.WhenAll(resetTasks);

                    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        logger.LogInformation("This shouldn't get through.");

                        Task completion = context.GetCompletion(sp);
                        replacedert.False(completion.IsCompleted);

                        completeCts.Cancel();

                        replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
                        replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
                    }
                }

                IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.UTF8, encoding);
                replacedert.Equal(new[]
                {
                    $"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This should get through.",
                    ""
                }, lines);
            }
            finally
            {
                Directory.Delete(logPath, recursive: true);
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

private void HaultAllProcessing()
		{
			if (_cancellationTokenSource != null && IsWorking)
			{
				_cancellationTokenSource.Cancel();
			}
		}

19 View Source File : MemoryFileProvider.cs
License : MIT License
Project Creator : adams85

public void WriteContent(string path, string content, Encoding encoding = null, bool append = false)
        {
            path = NormalizePath(path);

            CancellationTokenSource changeTokenSource = null;
            lock (_catalog)
                using (MemoryStream stream = GetStreamCore(path, out File file))
                {
                    if (content.Length == 0)
                        return;

                    if (!append)
                        stream.SetLength(0);
                    else
                        stream.Seek(0, SeekOrigin.End);

                    var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8);
                    writer.Write(content);
                    writer.Flush();

                    if (file.ChangeTokenSource != null)
                    {
                        changeTokenSource = file.ChangeTokenSource;
                        file.ChangeTokenSource = new CancellationTokenSource();
                    }
                }

            changeTokenSource?.Cancel();
        }

19 View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85

private async Task LoggingToPhysicalUsingDICore(LogFileAccessMode accessMode)
        {
            var logsDirName = Guid.NewGuid().ToString("D");

            var configData = new Dictionary<string, string>
            {
                [$"{nameof(FileLoggerOptions.BasePath)}"] = logsDirName,
                [$"{nameof(FileLoggerOptions.FileEncodingName)}"] = "UTF-16",
                [$"{nameof(FileLoggerOptions.DateFormat)}"] = "yyMMdd",
                [$"{nameof(FileLoggerOptions.FileAccessMode)}"] = accessMode.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.Path)}"] = "logger-<date>.log",
                [$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File"] = LogLevel.None.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.Information.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.Path)}"] = "test-<date>.log",
                [$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File.Test"] = LogLevel.Information.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.None.ToString(),
            };

            var cb = new ConfigurationBuilder();
            cb.AddInMemoryCollection(configData);
            IConfigurationRoot config = cb.Build();

            var tempPath = Path.Combine(Path.GetTempPath());
            var logPath = Path.Combine(tempPath, logsDirName);

            var fileProvider = new PhysicalFileProvider(tempPath);

            var cts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);

            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var diagnosticEventReceived = false;
            context.DiagnosticEvent += _ => diagnosticEventReceived = true;

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context, o => o.FileAppender = new PhysicalFileAppender(fileProvider)));
            services.Configure<FileLoggerOptions>(config);

            if (Directory.Exists(logPath))
                Directory.Delete(logPath, recursive: true);

            try
            {
                var ex = new Exception();

                FileLoggerProvider[] providers;

                using (ServiceProvider sp = services.BuildServiceProvider())
                {
                    providers = context.GetProviders(sp).ToArray();
                    replacedert.Equal(1, providers.Length);

                    ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();

                    logger1.LogInformation("This is a nice logger.");
                    using (logger1.BeginScope("SCOPE"))
                    {
                        logger1.LogWarning(1, "This is a smart logger.");
                        logger1.LogTrace("This won't make it.");

                        using (logger1.BeginScope("NESTED SCOPE"))
                        {
                            ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
                            ILogger logger2 = loggerFactory.CreateLogger("X");
                            logger2.LogError(0, ex, "Some failure!");
                        }
                    }

                    cts.Cancel();

                    // ensuring that all entries are processed
                    await context.GetCompletion(sp);
                    replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
                }

                replacedert.False(diagnosticEventReceived);

                IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.Unicode, encoding);
                replacedert.Equal(new[]
                {
                    $"info: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This is a nice logger.",
                    $"warn: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This is a smart logger.",
                    ""
                }, lines);

                logFile = fileProvider.GetFileInfo(
                    $"{logsDirName}/logger-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.Unicode, encoding);
                replacedert.Equal(new[]
                {
                    $"fail: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      Some failure!",
                }
                .Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
                .Append(""), lines);
            }
            finally
            {
                if (Directory.Exists(logPath))
                    Directory.Delete(logPath, recursive: true);
            }
        }

19 View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85

[Fact]
        public async Task LoggingToPhysicalUsingDIAndExpectingDiagnosticEvents()
        {
            var logsDirName = Guid.NewGuid().ToString("D");

            var tempPath = Path.Combine(Path.GetTempPath());
            var logPath = Path.Combine(tempPath, logsDirName);

            var fileProvider = new PhysicalFileProvider(tempPath);

            var cts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);

            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var diagnosticEvents = new List<IFileLoggerDiagnosticEvent>();
            context.DiagnosticEvent += diagnosticEvents.Add;

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context, o =>
            {
                o.FileAppender = new PhysicalFileAppender(fileProvider);
                o.BasePath = logsDirName;
                o.FileAccessMode = LogFileAccessMode.KeepOpen;
                o.Files = new[]
                {
                    new LogFileOptions
                    {
                        Path = "<invalid_filename>.log"
                    }
                };
            }));

            if (Directory.Exists(logPath))
                Directory.Delete(logPath, recursive: true);

            try
            {
                FileLoggerProvider[] providers;

                using (ServiceProvider sp = services.BuildServiceProvider())
                {
                    providers = context.GetProviders(sp).ToArray();
                    replacedert.Equal(1, providers.Length);

                    ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();

                    logger1.LogInformation("This is a nice logger.");
                    logger1.LogWarning(1, "This is a smart logger.");

                    cts.Cancel();

                    // ensuring that all entries are processed
                    await context.GetCompletion(sp);
                    replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
                }

                replacedert.NotEmpty(diagnosticEvents);
                replacedert.All(diagnosticEvents, e =>
                {
                    replacedert.IsType<FileLoggerDiagnosticEvent.LogEntryWriteFailed>(e);
                    replacedert.IsType<FileLoggerProcessor>(e.Source);
                    replacedert.NotNull(e.FormattableMessage);
                    replacedert.NotNull(e.Exception);
                });
            }
            finally
            {
                if (Directory.Exists(logPath))
                    Directory.Delete(logPath, recursive: true);
            }
        }

19 View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85

[Fact]
        public async Task LoggingToMemoryUsingCustomPathPlaceholderResolver()
        {
            const string appName = "myapp";
            const string logsDirName = "Logs";

            var fileProvider = new MemoryFileProvider();

            var cts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);

            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context, o =>
            {
                o.FileAppender = new MemoryFileAppender(fileProvider);
                o.BasePath = logsDirName;
                o.Files = new[]
                {
                    new LogFileOptions
                    {
                        Path = "<appname>-<counter:000>.log"
                    }
                };
                o.PathPlaceholderResolver = (placeholderName, inlineFormat, context) => placeholderName == "appname" ? appName : null;
            }));

            FileLoggerProvider[] providers;

            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                providers = context.GetProviders(sp).ToArray();
                replacedert.Equal(1, providers.Length);

                ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();

                logger1.LogInformation("This is a nice logger.");
                logger1.LogWarning(1, "This is a smart logger.");

                cts.Cancel();

                // ensuring that all entries are processed
                await context.GetCompletion(sp);
                replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
            }

            var logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/{appName}-000.log");
            replacedert.True(logFile.Exists && !logFile.IsDirectory);
        }

19 View Source File : HotReloadServer.cs
License : MIT License
Project Creator : adospace

public void Stop()
        {
            lock (this)
            {
                if (_cancellationTokenSource == null)
                    return;

                if (!_cancellationTokenSource.IsCancellationRequested)
                    _cancellationTokenSource.Cancel();
            }

            _serverSocket?.Stop();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : adospace

private static void Monitor(string replacedemblyPath)
        {
            var cancellationTokenSource = new CancellationTokenSource();

            Console.WriteLine($"Start listening '{replacedemblyPath}'");

            // Create a new FileSystemWatcher and set its properties.
            using var watcher = new FileSystemWatcher
            {
                Path = Path.GetDirectoryName(replacedemblyPath),

                // Watch for changes in LastAccess and LastWrite times, and
                // the renaming of files or directories.
                NotifyFilter = NotifyFilters.LastWrite,
                                //NotifyFilters.LastAccess
                                // | NotifyFilters.LastWrite
                                // | NotifyFilters.FileName
                                // | NotifyFilters.DirectoryName,

                // Only watch text files.
                Filter = Path.GetFileName(replacedemblyPath) //"*.txt"
            };

            // Add event handlers.
            watcher.Changed += OnChanged;
            //watcher.Created += OnChanged;
            //watcher.Deleted += OnChanged;
            //watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press Cancel Key to quit");
            //while (Console.Read() != 'q') ;

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cancellationTokenSource.Cancel();
            };

            cancellationTokenSource.Token.WaitHandle.WaitOne();

            cancellationTokenSource.Cancel();
        }

19 View Source File : Array.cs
License : MIT License
Project Creator : Adsito

public static float[,] Offset(float[,] array, float offset, bool clampOffset, Area dmns = null)
        {
            float[,] tempArray = array;
            CancellationTokenSource source = new CancellationTokenSource();
            ParallelOptions options = new ParallelOptions() { CancellationToken = source.Token};
            try
            {
                if (dmns == null)
                    dmns = AreaManager.ActiveArea;

                Parallel.For(dmns.x0, dmns.x1, options, i =>
                {
                    for (int j = dmns.z0; j < dmns.z1; j++)
                    {
                        if (clampOffset == true)
                        {
                            if ((array[i, j] + offset > 1f || array[i, j] + offset < 0f))
                                source.Cancel();
                            else
                                tempArray[i, j] += offset;
                        }
                        else
                            tempArray[i, j] += offset;
                    }
                });
            }
            catch (OperationCanceledException)
            {
                return array;
            }
            return tempArray;
        }

19 View Source File : MiningService.cs
License : MIT License
Project Creator : AElfProject

public async Task<BlockExecutedSet> MineAsync(RequestMiningDto requestMiningDto, List<Transaction> transactions,
            Timestamp blockTime)
        {
            try
            {
                using (var cts = new CancellationTokenSource())
                {
                    var expirationTime = blockTime + requestMiningDto.BlockExecutionTime;
                    if (expirationTime < TimestampHelper.GetUtcNow())
                        cts.Cancel();
                    else
                    {
                        var ts = (expirationTime - TimestampHelper.GetUtcNow()).ToTimeSpan();
                        if (ts.TotalMilliseconds > int.MaxValue)
                        {
                            ts = TimeSpan.FromMilliseconds(int.MaxValue);
                        }

                        cts.CancelAfter(ts);
                    }

                    var block = await GenerateBlock(requestMiningDto.PreviousBlockHash,
                        requestMiningDto.PreviousBlockHeight, blockTime);
                    var systemTransactions = await GenerateSystemTransactions(requestMiningDto.PreviousBlockHash,
                        requestMiningDto.PreviousBlockHeight);
                    _systemTransactionExtraDataProvider.SetSystemTransactionCount(systemTransactions.Count,
                        block.Header);
                    var txTotalCount = transactions.Count + systemTransactions.Count;

                    var pending = txTotalCount > requestMiningDto.TransactionCountLimit
                        ? transactions
                            .Take(requestMiningDto.TransactionCountLimit - systemTransactions.Count)
                            .ToList()
                        : transactions;
                    var blockExecutedSet = await _blockExecutingService.ExecuteBlockAsync(block.Header,
                        systemTransactions, pending, cts.Token);

                    block = blockExecutedSet.Block;
                    await SignBlockAsync(block);
                    Logger.LogInformation($"Generated block: {block.ToDiagnosticString()}, " +
                                          $"previous: {block.Header.PreviousBlockHash}, " +
                                          $"executed transactions: {block.Body.TransactionsCount}, " +
                                          $"not executed transactions {pending.Count + systemTransactions.Count - block.Body.TransactionsCount} ");
                    return blockExecutedSet;
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Failed while mining block.");
                throw;
            }
        }

19 View Source File : ResourceExtractionServiceTest.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public async Task GetResourcesAsync_Acs2_CancellationRequested_Test()
        {
            var cancelTokenSource = new CancellationTokenSource();
            cancelTokenSource.Cancel();
            var txn = GetAcs2Transaction(new ResourceInfo
            {
                WritePaths =
                {
                    GetPath(12345)
                }
            });
            var resourceInfos =
                (await Service.GetResourcesAsync(new Mock<IChainContext>().Object, new[] {txn}, cancelTokenSource.Token))
                .ToList();
            resourceInfos.Count.ShouldBe(1);
            resourceInfos.First().TransactionResourceInfo.ShouldBe(new TransactionResourceInfo()
            {
                TransactionId = txn.GetHash(),
                ParallelType = ParallelType.NonParallelizable
            });
        }

See More Examples