text stringlengths 0 13.4k |
|---|
var myCancellationToken = (CancellationToken)state; |
while(true) |
{ |
Console.Write("{0} ", i++); |
Thread.Sleep(1000); |
myCancellationToken.ThrowIfCancellationRequested(); |
} |
}, |
cancellationToken: cancellationToken, |
state: cancellationToken); |
Console.WriteLine("Counting to infinity. Press any key to cancel!"); |
task.Start(); |
Console.ReadKey(); |
cancellationTokenSource.Cancel(); |
try |
{ |
task.Wait(); |
} |
catch(AggregateException ex) |
{ |
ex.Handle(inner => inner is OperationCanceledException); |
} |
Console.WriteLine($"{Environment.NewLine}You have cancelled! Task status is: {task.Status}"); |
//Canceled |
As an alternative to ThrowIfCancellationRequested, the cancellation request can be detected with |
IsCancellationRequested and a OperationCanceledException can be thrown manually: |
//New task delegate |
GoalKicker.com – .NET Framework Notes for Professionals |
135 |
int i = 1; |
var myCancellationToken = (CancellationToken)state; |
while(!myCancellationToken.IsCancellationRequested) |
{ |
Console.Write("{0} ", i++); |
Thread.Sleep(1000); |
} |
Console.WriteLine($"{Environment.NewLine}Ouch, I have been cancelled!!"); |
throw new OperationCanceledException(myCancellationToken); |
Note how the cancellation token is passed to the task constructor in the cancellationToken parameter. This is |
needed so that the task transitions to the Canceled state, not to the Faulted state, when |
ThrowIfCancellationRequested is invoked. Also, for the same reason, the cancellation token is explicitly supplied |
in the constructor of OperationCanceledException in the second case. |
Section 42.15: Task.WhenAny |
var random = new Random(); |
IEnumerable<Task<int>> tasks = Enumerable.Range(1, 5).Select(n => Task.Run(async() => |
{ |
Console.WriteLine("I'm task " + n); |
await Task.Delay(random.Next(10,1000)); |
return n; |
})); |
Task<Task<int>> whenAnyTask = Task.WhenAny(tasks); |
Task<int> completedTask = await whenAnyTask; |
Console.WriteLine("The winner is: task " + await completedTask); |
await Task.WhenAll(tasks); |
Console.WriteLine("All tasks finished!"); |
GoalKicker.com – .NET Framework Notes for Professionals |
136 |
Chapter 43: Task Parallel Library (TPL) API |
Overviews |
Section 43.1: Perform work in response to a button click and |
update the UI |
This example demonstrates how you can respond to a button click by performing some work on a worker thread |
and then update the user interface to indicate completion |
void MyButton_OnClick(object sender, EventArgs args) |
{ |
Task.Run(() => // Schedule work using the thread pool |
{ |
System.Threading.Thread.Sleep(5000); // Sleep for 5 seconds to simulate work. |
}) |
.ContinueWith(p => // this continuation contains the 'update' code to run on the UI thread |
{ |
this.TextBlock_ResultText.Text = "The work completed at " + DateTime.Now.ToString() |
}, |
TaskScheduler.FromCurrentSynchronizationContext()); // make sure the update is run on the UI |
thread. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.