本文整理汇总了C#中System.Threading.CancellationTokenSource.Cancel方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource.Cancel方法的具体用法?C# CancellationTokenSource.Cancel怎么用?C# CancellationTokenSource.Cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CancellationTokenSource
的用法示例。
在下文中一共展示了CancellationTokenSource.Cancel方法的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: Validate
public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent)
{
var tasks = new List<Task<IYubicoResponse>>();
var cancellation = new CancellationTokenSource();
foreach (var url in urls)
{
var thisUrl = url;
var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token);
task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
tasks.Add(task);
task.Start();
}
while (tasks.Count != 0)
{
// TODO: handle exceptions from the verify task. Better to be able to propagate cause for error.
var completed = Task.WaitAny(tasks.Cast<Task>().ToArray());
var task = tasks[completed];
tasks.Remove(task);
if (task.Result != null)
{
cancellation.Cancel();
return task.Result;
}
}
return null;
}
示例3: Main
private static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress +=
(sender, e) =>
{
e.Cancel = true;
cts.Cancel();
};
// Since Console apps do not have a SyncronizationContext, we're leveraging the built-in support
// in WPF to pump the messages via the Dispatcher.
// See the following for additional details:
// http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx
// https://github.com/DotNetAnalyzers/StyleCopAnalyzers/pull/1362
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var context = new DispatcherSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(context);
DispatcherFrame dispatcherFrame = new DispatcherFrame();
Task mainTask = MainAsync(args, cts.Token);
mainTask.ContinueWith(task => dispatcherFrame.Continue = false);
Dispatcher.PushFrame(dispatcherFrame);
mainTask.GetAwaiter().GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
示例4: Start
public void Start(Func<Task> callback, TimeSpan? interval, Action<Exception> errorCallback)
{
tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
task = Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
try
{
if (interval.HasValue)
{
await Task.Delay(interval.Value, token).ConfigureAwait(false);
}
else
{
tokenSource.Cancel();
}
await callback().ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// nop
}
catch (Exception ex)
{
errorCallback(ex);
}
}
}, CancellationToken.None);
}
示例5: Dulicate_message_is_detected
public void Dulicate_message_is_detected()
{
var builder = new CqrsEngineBuilder();
builder.Memory(m =>
{
m.AddMemorySender("in", s => s.IdGenerator(() => "same"));
m.AddMemoryRouter("in", c => "memory:null");
});
var observer = new ImmediateEventsObserver();
builder.Advanced.RegisterObserver(observer);
using (var token = new CancellationTokenSource())
using (var build = builder.Build())
{
var sender = build.Resolve<IMessageSender>();
sender.SendOne(new Message());
sender.SendOne(new Message());
observer.Event += @event =>
{
var e = @event as EnvelopeDuplicateDiscarded;
if (e != null)
{
token.Cancel();
}
};
build.Start(token.Token);
token.Token.WaitHandle.WaitOne(10000);
Assert.IsTrue(token.IsCancellationRequested);
}
}
示例6: testCancellation
static void testCancellation()
{
IEnumerable<int> million = Enumerable.Range (3, 1000000);
var cancelSource = new CancellationTokenSource();
var primeNumberQuery =
from n in million.AsParallel().WithCancellation (cancelSource.Token)
where Enumerable.Range (2, (int) Math.Sqrt (n)).All (i => n % i > 0)
select n;
new Thread (() => {
Thread.Sleep (100); // Cancel query after
cancelSource.Cancel(); // 100 milliseconds.
}).Start();
try
{
// Start query running:
int[] primes = primeNumberQuery.ToArray();
// We'll never get here because the other thread will cancel us.
}
catch (OperationCanceledException)
{
Console.WriteLine("Query canceled");
}
}
示例7: Run
public void Run()
{
while (true)
{
var fetch = CommonTasks.ExecuteScript("Crawlers\\Scripts\\Bicing.js");
var parse = fetch.ContinueWith<Tuple<Station, NameValueCollection>[]>(Parse, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
var store = parse.ContinueWith(Store, TaskContinuationOptions.OnlyOnRanToCompletion);
try
{
Task.WaitAll(fetch, parse, store);
}
catch (AggregateException e)
{
e.Handle(x =>
{
System.Console.WriteLine(x.Message);
return true;
});
}
CancellationTokenSource source = new CancellationTokenSource();
Task.Factory.StartNew(() => StationLoop(parse.Result), source.Token);
Thread.Sleep(TimeSpan.FromHours(12));
source.Cancel();
}
}
示例8: NMSConnectionMonitor
/// <summary>
///
/// </summary>
/// <param name="connection">the connection to monitor for messages</param>
/// <param name="cts">cancellation token to cancel on error or no data received</param>
/// <param name="timeout">timeout to wait for messages</param>
public NMSConnectionMonitor(IConnection connection, CancellationTokenSource cts, TimeSpan? timeout = null)
{
QuitOk = true;
connection.ExceptionListener += (e) =>
{
Trace.TraceError("Connection error: {0}", e);
QuitOk = false;
cts.Cancel();
};
if (timeout.HasValue)
{
_timer = new Timer((state) =>
{
if (!connection.IsStarted ||
!_lastMsgRecd.HasValue ||
_lastMsgRecd.Value <= (DateTime.UtcNow.Subtract(timeout.Value)))
{
Trace.TraceInformation("Connection Monitor: Connection Stopped or No data recd for {0}, closing connection", timeout);
QuitOk = false;
cts.Cancel();
}
}, null, timeout.Value, timeout.Value);
}
}
示例9: Run
public async Task Run(CancellationToken cancel_token)
{
try {
cancel_token.ThrowIfCancellationRequested();
await Handshake(cancel_token);
var local_cancel = new CancellationTokenSource();
cancel_token.Register(() => { local_cancel.Cancel(); Close(); });
var send_messages = SendServerMessages(local_cancel.Token);
var recv_messages = RecvAndProcessMessages(local_cancel.Token);
Task.WaitAny(send_messages, recv_messages);
local_cancel.Cancel();
Close();
Task.WaitAll(send_messages, recv_messages);
}
catch (IOException e) {
if (!disposed) {
logger.Error(e);
}
}
catch (AggregateException e) {
if (!disposed) {
logger.Error(e);
}
}
finally {
Close();
}
}
示例10: Main
static void Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
var t2 = Task.Run(() =>
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine("In loop");
Thread.Sleep(1000);
}
}, cancellationToken)
.ContinueWith(prev =>
{
Console.WriteLine($"t2 status is now {prev.Status}");
});
cancellationToken.Register(() => { Console.WriteLine("this will run when cancelled"); });
Thread.Sleep(4000);
cancellationTokenSource.Cancel();
Console.ReadLine();
}
示例11: Queue
public static void Queue(
this IMessageBus messageBus,
ITest test,
Func<ITest, IMessageSinkMessage> createTestResultMessage,
CancellationTokenSource cancellationTokenSource)
{
Guard.AgainstNullArgument("messageBus", messageBus);
Guard.AgainstNullArgument("createTestResultMessage", createTestResultMessage);
Guard.AgainstNullArgument("cancellationTokenSource", cancellationTokenSource);
if (!messageBus.QueueMessage(new TestStarting(test)))
{
cancellationTokenSource.Cancel();
}
else
{
if (!messageBus.QueueMessage(createTestResultMessage(test)))
{
cancellationTokenSource.Cancel();
}
}
if (!messageBus.QueueMessage(new TestFinished(test, 0, null)))
{
cancellationTokenSource.Cancel();
}
}
示例12: LoadService
/// <summary>モジュール名を指定してモジュールをロードします。</summary>
/// <param name="serviceName">モジュール名</param>
/// <param name="args">モジュールロード時のオプション(使っていません)</param>
/// <returns>ロードされたモジュール</returns>
public async Task<QiServiceModule> LoadService(string serviceName, params object[] args)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(QiSession));
int id = PublishPostId();
QiServiceModule result = null;
JToken errorData = new JObject();
bool success = false;
bool disconnected = false;
CancellationTokenSource cts = new CancellationTokenSource();
var token = cts.Token;
//コードの通りだが、成功と失敗のイベントを監視しつつ通信を試す
using (var _ = Observable.FromEventPattern<QiSessionReplyEventArgs>(this, nameof(ReplyReceived))
.FirstAsync(ep => ep.EventArgs.Id == id)
.Subscribe(ep =>
{
success = true;
result = QiServiceModule.CreateFromMetaObject(this, ep.EventArgs.Data);
cts.Cancel();
}))
using (var __ = Observable.FromEventPattern<QiSessionReplyEventArgs>(this, nameof(ErrorReceived))
.FirstAsync(ep => ep.EventArgs.Id == id)
.Subscribe(ep =>
{
success = false;
errorData = ep.EventArgs.Data;
cts.Cancel();
}))
using (var ___ = Observable.FromEventPattern<EventArgs>(this, nameof(Disconnected))
.Take(1)
.Subscribe(____ =>
{
success = false;
disconnected = true;
cts.Cancel();
}))
{
Post(id, "ServiceDirectory", "service", new JArray(new JValue(serviceName)));
await Task.Delay(Timeout.Infinite, token);
if (disconnected)
{
throw new QiSessionDisconnectedException();
}
if(!success)
{
throw new QiSessionLoadServiceFailedException(id, serviceName, errorData);
}
return result;
}
}
示例13: Test
public void Test()
{
using (var source = new CancellationTokenSource())
{
var dev = AzureStorage.CreateConfigurationForDev();
WipeAzureAccount.Fast(s => s.StartsWith("test-"), dev);
var b = new RawEngineBuilder();
b.Dispatch(dev.CreateInbox("test-publish"), bytes =>
{
if (bytes[0] == 42)
source.Cancel();
});
using (var engine = b.Build())
{
var task = engine.Start(source.Token);
dev.CreateQueueWriter("test-publish").PutMessage(new byte[] {42});
if (!task.Wait(5000))
{
source.Cancel();
}
}
}
}
示例14: RunTestsAsync
/// <inheritdoc/>
protected override Task RunTestsAsync(IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
{
if (!messageBus.QueueMessage(new TestStarting(this, DisplayName)))
cancellationTokenSource.Cancel();
else
{
try
{
lambda();
if (!messageBus.QueueMessage(new TestPassed(this, DisplayName, 0, null)))
cancellationTokenSource.Cancel();
}
catch (Exception ex)
{
if (!messageBus.QueueMessage(new TestFailed(this, DisplayName, 0, null, ex)))
cancellationTokenSource.Cancel();
}
}
if (!messageBus.QueueMessage(new TestFinished(this, DisplayName, 0, null)))
cancellationTokenSource.Cancel();
return Task.FromResult(0);
}
示例15: RetrieveLights
public static async Task<List<Light>> RetrieveLights()
{
var cts = new CancellationTokenSource();
List<Light> retVal = new List<Light>();
cts.CancelAfter(5000);
try
{
HttpClient client = new HttpClient();
string ip, username;
int port;
SettingsService.RetrieveSettings(out ip, out port, out username);
var response = await client.GetAsync(new Uri(string.Format("http://{0}:{1}/api/{2}/lights/", ip, port, username))).AsTask(cts.Token);
if (!response.IsSuccessStatusCode)
{
cts.Cancel();
}
string jsonResponse = await response.Content.ReadAsStringAsync();
//System.Diagnostics.Debug.WriteLine(jsonResponse);
retVal = ParseLights(jsonResponse);
var IgnoredTask = UpdateLightsPhraseList(retVal);
IgnoredTask.Start();
}
catch (Exception)
{
cts.Cancel();
}
return retVal;
}