本文整理汇总了C#中System.Threading.CancellationToken.Register方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationToken.Register方法的具体用法?C# CancellationToken.Register怎么用?C# CancellationToken.Register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CancellationToken
的用法示例。
在下文中一共展示了CancellationToken.Register方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SearchAsync
public Task SearchAsync(string searchPattern, FileSearchMode mode, int count, IFileCollection files, CancellationToken cancellationToken)
{
if (String.IsNullOrEmpty(searchPattern))
{
files.Clear();
foreach (string filePath in pinStateService.GetList())
files.Add(Path.GetFileNameWithoutExtension(filePath), filePath, true);
if (lastCancellation != null)
{
lastCancellation.Cancel();
lastCancellation = null;
}
return Task.FromResult(true);
}
if (cancellationToken.IsCancellationRequested)
return Async.CompletedTask;
lastCancellation = new CancellationTokenSource();
cancellationToken.Register(() => lastCancellation.Cancel());
Task result = innerService.SearchAsync(searchPattern, mode, count, files, lastCancellation.Token);
return result;
}
开发者ID:neptuo,项目名称:Productivity.SolutionRunner,代码行数:26,代码来源:PinnedForEmptyPatternFileSearchService.cs
示例2: CancellationTokenRegister_Exceptions
public static void CancellationTokenRegister_Exceptions()
{
CancellationToken token = new CancellationToken();
Assert.Throws<ArgumentNullException>(() => token.Register(null));
Assert.Throws<ArgumentNullException>(() => token.Register(null, false));
Assert.Throws<ArgumentNullException>(() => token.Register(null, null));
}
示例3: Run
public void Run(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return;
cancellationToken.Register(() => Receiver.CancelMessageWait());
while (true)
{
if (cancellationToken.IsCancellationRequested)
break;
string currentMessage = null;
try
{
currentMessage = Receiver.GetNextMessage();
if (cancellationToken.IsCancellationRequested)
break;
ProcessMessage(currentMessage, cancellationToken);
Receiver.AckLastMessage();
}
catch (Exception ex)
{
Log.ErrorFormat(CultureInfo.InvariantCulture,
"Worker {0} encountered an error while attempting to process the message \"{1}\".",
InstanceId, currentMessage
);
Log.Error(ex);
Receiver.NackLastMessage();
}
}
}
示例4: RunAsync
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
{
if (processStartInfo == null)
{
throw new ArgumentNullException("processStartInfo");
}
// force some settings in the start info so we can capture the output
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.CreateNoWindow = true;
var tcs = new TaskCompletionSource<ProcessResults>();
var standardOutput = new List<string>();
var standardError = new List<string>();
var process = new Process
{
StartInfo = processStartInfo,
EnableRaisingEvents = true,
};
process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
standardOutput.Add(args.Data);
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
standardError.Add(args.Data);
}
};
process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));
cancellationToken.Register(() =>
{
tcs.TrySetCanceled();
process.CloseMainWindow();
});
cancellationToken.ThrowIfCancellationRequested();
if (process.Start() == false)
{
tcs.TrySetException(new InvalidOperationException("Failed to start process"));
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return tcs.Task;
}
示例5: ReadMultipartAsync
public static async Task<IMultipartCollection> ReadMultipartAsync(this HttpRequest request, CancellationToken cancellationToken) {
cancellationToken.ThrowIfCancellationRequested();
request.EnableRewind();
var parts = new MultipartCollection();
using(cancellationToken.Register(request.HttpContext.Abort)) {
var contentType = GetContentType(request);
var boundary = GetBoundary(contentType);
var multipartReader = new MultipartReader(boundary, request.Body);
var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
while(section != null) {
var headers = new HeaderDictionary(section.Headers);
var contentDisposition = headers.GetContentDisposition();
await section.Body.DrainAsync(cancellationToken);
var part = new Multipart(request.Body, section.BaseStreamOffset.Value, section.Body.Length) {
Headers = headers
};
parts.Add(part);
section = await multipartReader.ReadNextSectionAsync(cancellationToken);
}
}
request.Body.Seek(0, SeekOrigin.Begin);
return parts;
}
示例6: UploadFromStreamAsync
public static Task UploadFromStreamAsync(
this CloudBlockBlob blob, Stream stream, CancellationToken ct = default(CancellationToken))
{
ICancellableAsyncResult ar = blob.BeginUploadFromStream(stream, null, null);
ct.Register(ar.Cancel);
return Task.Factory.FromAsync(ar, blob.EndUploadFromStream);
}
示例7: RSessionEvaluation
public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) {
Contexts = contexts;
_evaluator = evaluator;
_tcs = new TaskCompletionSource<object>();
_ct = ct;
ct.Register(() => _tcs.TrySetCanceled());
}
示例8: Run
public static void Run(this IWebHost host, Action<IServiceProvider> action, CancellationToken token, string shutdownMessage)
{
using (host)
{
host.Start();
var hostingEnvironment = host.Services.GetService<IHostingEnvironment>();
var applicationLifetime = host.Services.GetService<IApplicationLifetime>();
Console.WriteLine($"Hosting environment: {hostingEnvironment.EnvironmentName}");
Console.WriteLine($"Content root path: {hostingEnvironment.ContentRootPath}");
var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
if (serverAddresses != null)
{
foreach (var address in serverAddresses)
{
Console.WriteLine($"Now listening on: {address}");
}
}
if (!string.IsNullOrEmpty(shutdownMessage))
{
Console.WriteLine(shutdownMessage);
}
token.Register(state =>
{
((IApplicationLifetime)state).StopApplication();
},
applicationLifetime);
action(host.Services);
}
}
示例9: Run
public async Task Run(CancellationToken token)
{
var tcs = new TaskCompletionSource<bool>();
token.Register(() => { this.receiver.Close(); tcs.SetResult(true); });
this.receiver.OnMessageAsync(rq => this.Respond(rq, this.responseFunction), new OnMessageOptions { AutoComplete = false });
await tcs.Task;
}
示例10: ConnectAsync
public async Task ConnectAsync(string webSocketServerUrl, CancellationToken token)
{
var uri = default(Uri);
if (!Uri.TryCreate(webSocketServerUrl, UriKind.Absolute, out uri))
{
throw new ArgumentOutOfRangeException(nameof(webSocketServerUrl), "Expected valid URI argument.");
}
var retryCount = ConnectRetryCount;
while (true)
{
var timeoutSource = new CancellationTokenSource(ConnectTimeoutMilliseconds);
using (token.Register(timeoutSource.Cancel))
{
try
{
await ConnectCoreAsync(uri, timeoutSource.Token).ConfigureAwait(false);
return;
}
catch (OperationCanceledException ex)
when (ex.CancellationToken == timeoutSource.Token)
{
token.ThrowIfCancellationRequested();
}
catch
{
if (--retryCount <= 0)
{
throw;
}
}
}
}
}
示例11: Run
private async Task Run(string directory, CancellationToken token)
{
var applicationBase = Environment.CurrentDirectory;
var abPrefix = applicationBase.Length + 1;
var relBoot = Path.GetDirectoryName(Path.GetFullPath(typeof(Boot).Assembly.Location).Substring(abPrefix));
var relDir = Path.GetFullPath(directory).Substring(abPrefix);
if (!token.IsCancellationRequested)
{
// ReSharper disable AccessToDisposedClosure
var isolated = new Isolate<IsolatedRunner, IIsolatedRunner>(null, new AppDomainSetup { ApplicationBase = applicationBase, PrivateBinPath = relDir + Path.PathSeparator + relBoot });
using(isolated)
{
var reg = token.Register(() => isolated.Value.Cancel());using (reg)
try
{
Debug.WriteLine("Start " + directory);
await Task.Factory.StartNew(() => isolated.Value.Run(), token);
}
catch (TaskCanceledException)
{
}
catch (Exception ex)
{
_log.Log(2, "Boot Run: " + ex.ToString());
}
Debug.WriteLine("Finish " + directory);
}
// ReSharper restore AccessToDisposedClosure
}
}
示例12: GetWorkspaceAsync
/// <summary>
/// Get's the primary workspace asynchronously.
/// </summary>
public static Task<Workspace> GetWorkspaceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (s_registryGate.DisposableWrite())
{
if (s_primaryWorkspace != null)
{
return Task<Workspace>.FromResult(s_primaryWorkspace);
}
else
{
var taskSource = new TaskCompletionSource<Workspace>();
if (cancellationToken.CanBeCanceled)
{
try
{
var registration = cancellationToken.Register(() =>
{
taskSource.TrySetCanceled();
});
taskSource.Task.ContinueWith(_ => registration.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
catch
{
}
}
s_primaryWorkspaceTaskSourceList.Add(taskSource);
return taskSource.Task;
}
}
}
示例13: GetIntAsync
public static Task<int> GetIntAsync(CancellationToken token = default(CancellationToken))
{
var tcs = new TaskCompletionSource<int>();
if (token.IsCancellationRequested)
{
tcs.SetCanceled();
return tcs.Task;
}
var timer = new System.Timers.Timer(3000);
timer.AutoReset = false;
timer.Elapsed += (s, e) =>
{
tcs.TrySetResult(10);
timer.Dispose();
};
if (token.CanBeCanceled)
{
token.Register(() => {
tcs.TrySetCanceled();
timer.Dispose();
});
}
timer.Start();
return tcs.Task;
}
示例14: WaitForChangeAsync
public async Task<string> WaitForChangeAsync(CancellationToken cancellationToken)
{
_watchedFiles = GetProjectFilesClosure(_rootProject);
foreach (var file in _watchedFiles)
{
_fileWatcher.WatchDirectory(Path.GetDirectoryName(file));
}
var tcs = new TaskCompletionSource<string>();
cancellationToken.Register(() => tcs.TrySetResult(null));
Action<string> callback = path =>
{
// If perf becomes a problem, this could be a good starting point
// because it reparses the project on every change
// Maybe it could time-buffer the changes in case there are a lot
// of files changed at the same time
if (IsFileInTheWatchedSet(path))
{
tcs.TrySetResult(path);
}
};
_fileWatcher.OnFileChange += callback;
var changedFile = await tcs.Task;
_fileWatcher.OnFileChange -= callback;
return changedFile;
}
示例15: Start
public Task Start(CancellationToken cancellationToken)
{
var completion = new TaskCompletionSource<bool>();
cancellationToken.Register(() => ProcessExtensions.Terminate(_process));
// Hook up the events. We don't hook up OutputDataReceived, because that wants to treat the data as strings; we need binary.
_process.ErrorDataReceived += (sender, e) => OnErrorDataReceived(new ErrorDataReceivedEventArgs(e.Data));
_process.Exited += (sender, e) =>
{
_process.WaitForExit(1000);
_process.StandardOutput.Close();
if (_process.ExitCode == 0)
completion.SetResult(true);
else if (cancellationToken.IsCancellationRequested)
completion.SetCanceled();
else
completion.SetException(new CodecProcessFailedException(_process.ExitCode));
};
_process.Start();
_process.PriorityClass = ProcessPriorityClass.BelowNormal;
_process.BeginErrorReadLine();
return completion.Task;
}