本文整理汇总了C#中CancellationTokenSource类的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource类的具体用法?C# CancellationTokenSource怎么用?C# CancellationTokenSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CancellationTokenSource类属于命名空间,在下文中一共展示了CancellationTokenSource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CancellationTokenSource
public void Cancel時にRegisterで登録したデリゲートが呼ばれる()
{
var runner = new SampleTaskRunner.TaskRunner();
{
// キャンセルしない場合
var cts = new CancellationTokenSource();
var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
t.Start(runner);
runner.Update(20);
Assert.IsTrue(t.IsCompleted);
Assert.AreEqual(CompletedMessage, t.Result);
}
{
// キャンセルする場合
var cts = new CancellationTokenSource();
var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
t.Start(runner);
runner.Update(5);
cts.Cancel();
runner.Update(5);
Assert.IsTrue(t.IsCompleted);
Assert.AreEqual(CanceledMessage, t.Result);
}
}
示例2: Main
public static void Main(String[] args)
{
Console.WriteLine("\n-- Cancellation with acknowledgement -------------");
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task task = Task.Run(() => ComputeTaskWithAcknowledgement(token), token);
Thread.Sleep(0); // Allow task to be scheduled
Console.WriteLine(task.Status); // Running
cts.Cancel();
Thread.Sleep(0);
Console.WriteLine(task.Status); // Canceled
try {
task.Wait(); // Throws AggregateException containing TaskCanceledException
} catch (Exception exn) {
Console.WriteLine("Caught " + exn);
}
Console.WriteLine(task.Status); // Canceled
}
Console.WriteLine("\n-- Cancellation without acknowledgement ----------");
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task task = Task.Run(() => ComputeTaskWithoutAcknowledgement(token), token);
Thread.Sleep(0);
Console.WriteLine(task.Status); // Running
cts.Cancel();
Console.WriteLine(task.Status); // Running
task.Wait();
Console.WriteLine(task.Status); // RanToCompletion
}
Console.WriteLine("\n-- Cancellation before Start ---------------------");
{
// Cancel before running
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task task = new Task(delegate { }, token);
Console.WriteLine(task.Status); // Created
cts.Cancel();
Console.WriteLine(task.Status); // Canceled
try {
task.Start(); // Throws InvalidOperationException
} catch (Exception exn) {
Console.WriteLine("Caught " + exn);
}
Console.WriteLine(task.Status); // Canceled
}
Console.WriteLine("\n-- Completing before cancellation ----------------");
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task task = new Task(delegate { }, token);
Console.WriteLine(task.Status); // Created
task.Start();
Thread.Sleep(0); // Allow task to be scheduled
Console.WriteLine(task.Status); // RanToCompletion
cts.Cancel();
Console.WriteLine(task.Status); // RanToCompletion
}
}
示例3: OutboxCleaner
public OutboxCleaner(OutboxPersister outboxPersister, TimeSpan timeToKeepDeduplicationData, TimeSpan frequencyToRunCleanup)
{
cancellationTokenSource = new CancellationTokenSource();
this.timeToKeepDeduplicationData = timeToKeepDeduplicationData;
this.frequencyToRunCleanup = frequencyToRunCleanup;
this.outboxPersister = outboxPersister;
}
示例4: TestCancel
public void TestCancel()
{
using (var waitHandle = new ManualResetEvent(false))
{
// Monitor for a cancellation exception
var task = new WaitTask("Test task", waitHandle);
bool exceptionThrown = false;
var cancellationTokenSource = new CancellationTokenSource();
var waitThread = new Thread(() =>
{
try
{
task.Run(cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
exceptionThrown = true;
}
});
// Start and then cancel the download
waitThread.Start();
Thread.Sleep(100);
cancellationTokenSource.Cancel();
waitThread.Join();
exceptionThrown.Should().BeTrue(because: task.State.ToString());
}
}
示例5: Main
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
var ct = cts.Token;
Task task1 = new Task(() => { Run1(ct); }, ct);
Task task2 = new Task(Run2);
try
{
task1.Start();
task2.Start();
Thread.Sleep(1000);
cts.Cancel();
Task.WaitAll(task1, task2);
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("\nhi,我是OperationCanceledException:{0}\n", e.Message);
}
//task1是否取消
Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled);
Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled);
}
Console.Read();
}
示例6: Start
public void Start(IRequestObject requestObject)
{
if (requestObject == null)
return;
if (IsBusy)
return;
_cancellationTokenSource = new CancellationTokenSource();
_isBusy = true;
this._requestObject = requestObject;
var token = _cancellationTokenSource.Token;
Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
var now = DateTime.Now;
if (this._requestObject.CanCreateRequst && now >= NextRequestTme)
{
NextRequestTme = now.AddSeconds(IntervalSeconds);
HandleRequestAsync();
}
System.Threading.Thread.Sleep(500);
}
_isBusy = false;
}, _cancellationTokenSource.Token);
}
示例7: Main
static void Main() {
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task job = Task.Factory.StartNew(() => {
for (int i = 0; i < 8; ++i) {
Console.WriteLine("STEP #{0}", i);
Thread.Sleep(1000);
token.ThrowIfCancellationRequested();
}
Console.WriteLine("DONE");
}, token);
//Thread.Sleep(3500);
//cts.Cancel();
cts.CancelAfter(3500);
Console.WriteLine("(cancellation requested)");
try {
job.Wait();
} catch (Exception) {
Console.WriteLine("(exception caught)");
}
Console.WriteLine("FINISHED IN STATE : {0}", job.Status);
}
示例8: Main
static int Main(string[] args)
{
SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);
var cts = new CancellationTokenSource();
s.Wait();
var t = s.WaitAsync(cts.Token);
s.Release();
cts.Cancel();
if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
return 101;
}
}
示例9: Main
public static void Main(){
CancellationTokenSource cancelTokenSrc = new CancellationTokenSource();
Task<Int32> t = new Task<Int32>(
() => { return Sum(100000000, cancelTokenSrc.Token);},
cancelTokenSrc.Token);
t.Start();
cancelTokenSrc.Cancel();
Thread.Sleep(1000);
try{
Console.WriteLine("Waiting...............");
t.Wait();
}catch(AggregateException ex){
ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
}
try{
Console.WriteLine("Extracting Result");
Console.WriteLine("The Sum is: " + t.Result); // An Int32 value
}catch(AggregateException ex){
ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
}
}
示例10: CreateTestClass
/// <summary>
/// Creates an instance of the test class for the given test case. Sends the <see cref="ITestClassConstructionStarting"/>
/// and <see cref="ITestClassConstructionFinished"/> messages as appropriate.
/// </summary>
/// <param name="testCase">The test case</param>
/// <param name="testClassType">The type of the test class</param>
/// <param name="constructorArguments">The constructor arguments for the test class</param>
/// <param name="displayName">The display name of the test case</param>
/// <param name="messageBus">The message bus used to send the test messages</param>
/// <param name="timer">The timer used to measure the time taken for construction</param>
/// <param name="cancellationTokenSource">The cancellation token source</param>
/// <returns></returns>
public static object CreateTestClass(this ITestCase testCase,
Type testClassType,
object[] constructorArguments,
string displayName,
IMessageBus messageBus,
ExecutionTimer timer,
CancellationTokenSource cancellationTokenSource)
{
object testClass = null;
if (!messageBus.QueueMessage(new TestClassConstructionStarting(testCase, displayName)))
cancellationTokenSource.Cancel();
try
{
if (!cancellationTokenSource.IsCancellationRequested)
timer.Aggregate(() => testClass = Activator.CreateInstance(testClassType, constructorArguments));
}
finally
{
if (!messageBus.QueueMessage(new TestClassConstructionFinished(testCase, displayName)))
cancellationTokenSource.Cancel();
}
return testClass;
}
示例11: FireReconnected
private static void FireReconnected(IConnection connection,
CancellationTokenSource reconnectTokenSource,
ref int reconnectedFired)
{
if (!reconnectTokenSource.IsCancellationRequested
&& Interlocked.Exchange(ref reconnectedFired, 1) == 0)
connection.OnReconnected();
}
示例12: CancellationToken
public CancellationToken(bool canceled)
: this()
{
initialized = true;
canBeCanceled = canceled;
// This is correctly set later if token originates from a Source
source = canceled ? CancellationTokenSource.CanceledSource : CancellationTokenSource.NoneSource;
}
示例13: FactDiscovererTests
public FactDiscovererTests()
{
aggregator = new ExceptionAggregator();
cancellationTokenSource = new CancellationTokenSource();
factAttribute = Mocks.FactAttribute();
messageBus = new SpyMessageBus();
options = TestFrameworkOptions.ForDiscovery();
}
示例14: Precancellation
public void Precancellation()
{
IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42));
var cts = new CancellationTokenSource();
cts.Cancel();
AssertSynchronouslyCanceled(c.WaitToReadAsync(cts.Token), cts.Token);
AssertSynchronouslyCanceled(c.ReadAsync(cts.Token).AsTask(), cts.Token);
}
示例15: doStuff
public void doStuff(string exampleString)
{
cancelSource = new CancellationTokenSource();
cancelToken = cancelSource.Token;
var decRep = new Progress<decimal>((decCount) =>
{
if (PctChangedEvent != null) PctChangedEvent(decCount);
});
Task.Run(() => { doStuffTask(exampleString, decRep, cancelToken); });
}