本文整理汇总了C#中System.Threading.CancellationTokenSource类的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource类的具体用法?C# CancellationTokenSource怎么用?C# CancellationTokenSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CancellationTokenSource类属于System.Threading命名空间,在下文中一共展示了CancellationTokenSource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateFirstCrossWord
static ICrossBoard GenerateFirstCrossWord(ICrossBoard board, ICrossDictionary dictionary, string puzzle)
{
var placer = new PuzzlePlacer(board, puzzle);
var cts = new CancellationTokenSource();
var mre = new ManualResetEvent(false);
ICrossBoard successFullBoard = null;
foreach (var boardWithPuzzle in placer.GetAllPossiblePlacements(dictionary))
{
//boardWithPuzzle.WriteTo(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true });
var gen = new CrossGenerator(dictionary, boardWithPuzzle);
var t = Task.Factory.StartNew(() =>
{
foreach (var solution in gen.Generate())
{
successFullBoard = solution;
cts.Cancel();
mre.Set();
break; //interested in the first one
}
}, cts.Token);
if (cts.IsCancellationRequested)
break;
}
mre.WaitOne();
return successFullBoard;
}
示例2: 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");
}
}
示例3: 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();
}
}
示例4: 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);
}
}
示例5: GetDelegateTypes
public static List<ClrType> GetDelegateTypes(ClrDump clrDump)
{
CancellationTokenSource token = new CancellationTokenSource();
clrDump.MessageBus.BeginTask("Analyzing delegate types...", token);
List<ClrType> delegates = new List<ClrType>();
var delegateType = clrDump.GetClrType(typeof(MulticastDelegate).FullName);
foreach(var type in clrDump.AllTypes)
{
clrDump.MessageBus.Status($"Analyzing delegate type: {type.Name}");
if (token.IsCancellationRequested)
{
break;
}
if ( type.BaseType != null && type.BaseType == delegateType )
{
clrDump.MessageBus.Status($"Analyzing delegate type: counting instances for {type.Name}");
int nb = clrDump.CountInstances(type);
if (nb > 0)
{
delegates.Add(type);
}
}
}
clrDump.MessageBus.EndTask("Delegate types analyzed.");
return delegates.GroupBy(t => t.Name).Select(g => g.First()).ToList();
}
示例6: GeneratePasswords
//probe==StartBounder
public bool GeneratePasswords(int[] probe, int[] startBoundary, int[] endBoundary, int depth, int range, CancellationToken ct, CancellationTokenSource tokenSource, Action<string> sendPassword)
{
bool result = false;
char[] probeChar = CharForThread(probe, _options);
string probeString = String.Join("", probeChar);
if (depth==0)
{
Console.WriteLine(probeString);
if (VerifyMd5Hash(probeString))
{
Password = probeString;
sendPassword(Password);
return true;
}
return false;
}
if (ct.IsCancellationRequested)
{
Console.WriteLine("Task is canceled");
}
if (probe.SequenceEqual(endBoundary)) return false;
for (int i = 0; i < range; i++)
{
probe[depth - 1] = i;
result = GeneratePasswords(probe, startBoundary, endBoundary, depth - 1, range, ct, tokenSource, sendPassword);
if (result) break;
}
return result;
}
示例7: Start
public async Task Start(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Settings.Default.Reload();
var imageInfo = GetLatestImageInfo();
if (imageInfo != null)
{
var image = AssembleImageFrom(imageInfo);
var imageFile = SaveImage(image);
Wallpaper.Set(imageFile, Wallpaper.Style.Fit);
}
if (Settings.Default.Interval > 0)
{
_internalTokenSource = new CancellationTokenSource();
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, token))
{
try
{
await Task.Delay(TimeSpan.FromMinutes(Settings.Default.Interval), linkedCts.Token);
}
catch
{
// ignore exception raised by token cancellation
}
}
}
}
}
示例8: 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);
}
}
示例9: 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
示例10: WhenProcessTimesOut_TaskIsCanceled
public void WhenProcessTimesOut_TaskIsCanceled()
{
// Arrange
const int expectedExitCode = 123;
const int millisecondsForTimeout = 3 * 1000;
const int millisecondsToSleep = 5 * 1000;
const int expectedStandardOutputLineCount = 5;
const int expectedStandardErrorLineCount = 3;
// Act
var pathToConsoleApp = typeof(DummyConsoleApp.Program).Assembly.Location;
var arguments = String.Join(" ", expectedExitCode, millisecondsToSleep, expectedStandardOutputLineCount, expectedStandardErrorLineCount);
var startInfo = new ProcessStartInfo(pathToConsoleApp, arguments);
var cancellationToken = new CancellationTokenSource(millisecondsForTimeout).Token;
var task = ProcessEx.RunAsync(startInfo, cancellationToken);
// Assert
Assert.IsNotNull(task);
try
{
var results = task.Result;
Assert.Fail("Timeout did not occur");
}
catch (AggregateException aggregateException)
{
// expected
Assert.AreEqual(1, aggregateException.InnerExceptions.Count);
var innerException = aggregateException.InnerExceptions.Single();
Assert.IsInstanceOfType(innerException, typeof(OperationCanceledException));
var canceledException = innerException as OperationCanceledException;
Assert.IsNotNull(canceledException);
Assert.IsTrue(cancellationToken.IsCancellationRequested);
}
Assert.AreEqual(TaskStatus.Canceled, task.Status);
}
示例11: Application_Start
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
var ts = new CancellationTokenSource();
var host = Bootstrapper.Boot();
host.Start(ts.Token);
// var bus = new FakeBus();
//
// var storage = new EventStore(bus);
// var rep = new Repository<InventoryItem>(storage);
// var commands = new InventoryCommandHandlers(rep);
// bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle);
// bus.RegisterHandler<CreateInventoryItem>(commands.Handle);
// bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle);
// bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle);
// bus.RegisterHandler<RenameInventoryItem>(commands.Handle);
// var detail = new InvenotryItemDetailView();
// bus.RegisterHandler<InventoryItemCreated>(detail.Handle);
// bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle);
// bus.RegisterHandler<InventoryItemRenamed>(detail.Handle);
// bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle);
// bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle);
// var list = new InventoryListView();
// bus.RegisterHandler<InventoryItemCreated>(list.Handle);
// bus.RegisterHandler<InventoryItemRenamed>(list.Handle);
// bus.RegisterHandler<InventoryItemDeactivated>(list.Handle);
// ServiceLocator.Bus = bus;
}
示例12: DatabaseBulkOperations
public DatabaseBulkOperations(DocumentDatabase database, TransactionInformation transactionInformation, CancellationTokenSource tokenSource, CancellationTimeout timeout)
{
this.database = database;
this.transactionInformation = transactionInformation;
this.tokenSource = tokenSource;
this.timeout = timeout;
}
示例13: CommandProcessor
public CommandProcessor(ICommandProcessingStrategy processingStrategy,
ICommandQueue commandQueue)
{
_processingStrategy = processingStrategy;
_commandQueue = commandQueue;
_cancellationTokenSource = new CancellationTokenSource();
var token = _cancellationTokenSource.Token;
var task = new Task(
() =>
{
while (!token.IsCancellationRequested)
{
var cmd = _commandQueue.Dequeue();
while (cmd != null)
{
_processingStrategy.ProcessCommand(cmd.Execute);
cmd = commandQueue.Dequeue();
}
Thread.Sleep(100);
}
},
token,
TaskCreationOptions.LongRunning);
task.Start();
}
示例14: BuildInGui
/// <summary>
/// Starts to run a build inside the SharpDevelop GUI.
/// Only one build can run inside the GUI at one time.
/// </summary>
/// <param name="project">The project/solution to build.</param>
/// <param name="options">The build options.</param>
public static void BuildInGui(IBuildable project, BuildOptions options)
{
if (project == null)
throw new ArgumentNullException("project");
if (options == null)
throw new ArgumentNullException("options");
WorkbenchSingleton.AssertMainThread();
if (guiBuildCancellation != null) {
BuildResults results = new BuildResults();
WorkbenchSingleton.StatusBar.SetMessage(Core.ResourceService.GetString("MainWindow.CompilerMessages.MSBuildAlreadyRunning"));
BuildError error = new BuildError(null, Core.ResourceService.GetString("MainWindow.CompilerMessages.MSBuildAlreadyRunning"));
results.Add(error);
TaskService.Add(new Task(error));
results.Result = BuildResultCode.MSBuildAlreadyRunning;
if (options.Callback != null) {
options.Callback(results);
}
} else {
guiBuildCancellation = new CancellationTokenSource();
IProgressMonitor progressMonitor = WorkbenchSingleton.StatusBar.CreateProgressMonitor(guiBuildCancellation.Token);
guiBuildTrackedFeature = AnalyticsMonitorService.TrackFeature("ICSharpCode.SharpDevelop.Project.BuildEngine.Build");
WorkbenchSingleton.StatusBar.SetMessage(StringParser.Parse("${res:MainWindow.CompilerMessages.BuildVerb}..."));
ProjectService.RaiseEventBuildStarted(new BuildEventArgs(project, options));
StartBuild(project, options,
new MessageViewSink(TaskService.BuildMessageViewCategory, progressMonitor, WorkbenchSingleton.StatusBar));
}
}
示例15: GetQuickLocation
public async Task<XLocation> GetQuickLocation()
{
Setup();
var loc = new XLocation();
_cancelSource = new CancellationTokenSource();
await _geolocator.GetPositionAsync(1500, _cancelSource.Token, false)
.ContinueWith(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
var x = new XLocation();
x.IsResolved = false;
x.Status = XPositionStatus.NotAvailble;
return x;
}
loc.Latitude = t.Result.Latitude;
loc.Longitude = t.Result.Longitude;
loc.Accuracy = t.Result.Accuracy;
loc.Heading = t.Result.Heading;
loc.IsEnabled = true;
loc.IsResolved = true;
loc.Status = XPositionStatus.Ready;
return loc;
}, _scheduler);
return loc;
}