Multi-thread Task: task base, multitask parallel execution, parallel operation (Parallel)
Introduced
Re-imagine the task of Windows 8 Store Apps
Task-tasks based on the thread pool (under the System.Threading.Tasks namespace)
Concurrent execution of multiple tasks
Parallel-Parallel computing (under the System.Threading.Tasks namespace)
Example
1. The basic application of the task (based on thread pool)
Thread/tasks/taskdemo.xaml
<page x:class= "XamlDemo.Thread.Tasks.TaskDemo" xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentati On "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" Using:XamlDemo.Thread.Tasks "xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "xmlns:mc=" http://schemas.openxmlformats.org/ markup-compatibility/2006 "mc:ignorable=" D "> <grid background=" Transparent "> <stackpanel margin= "0 0 0" > <textblock name= "lblmsg" fontsize= "14.667"/> <button Na Me= "Btncreatetask" content= "perform a task with no return value" click= "Btncreatetask_click_1" margin= "0 0 0"/> <button Nam
E= "Btncanceltask" content= Cancel "perform a task with no return value" "Click= btncanceltask_click_1" margin= "0 0 0"/> <button name= "Btncreatetaskwithreturn" content= "performs a task with a return value" click= "Btncreatetaskwithreturn_click_1" Margin= "0 3 0 0 0 "/> <button name=" BtncanCeltaskwithreturn "content=" cancels "perform a task with a return value" "click=" Btncanceltaskwithreturn_click_1 "margin=" 0 0 0 "/> </StackPanel> </Grid> </Page>
Thread/tasks/taskdemo.xaml.cs
* * task-based on thread pool tasks (under the System.Threading.Tasks namespace) * * using System;
Using Windows.UI.Xaml;
Using Windows.UI.Xaml.Controls;
Using System.Threading.Tasks;
Using System.Threading;
Using Windows.UI.Core; Namespace XamlDemo.Thread.Tasks {public sealed partial class Taskdemo:page {* * * cancellation Tokensource-For canceling CancellationToken * Token-an object of CancellationToken type, for associating Task * Iscancell Ationrequested-Did you receive a cancellation request * Cancel ()-Request to cancel operation * CancellationToken-for associating Task To cancel Task * iscancellationrequested-whether a request to cancel the operation was received * WaitHandle-signal, which can be passed through WaitHandle.WaitOne ()
Waits on the current thread * throwifcancellationrequested ()-If a request to cancel is received, a OperationCanceledException exception is thrown.
Private CancellationTokenSource _cts; Public Taskdemo () {this.
InitializeComponent (); } private void Btncreatetask_clicK_1 (object sender, RoutedEventArgs e) {_cts = new CancellationTokenSource (); Instantiate a task, and you can pass it at any time.
Status Gets the task status tasks = new Task (CTX) =>//task called method, no return value { Blocks 3000 milliseconds on the current thread (signals when a cancellation request is received and stops blocking) _cts.
Token.WaitHandle.WaitOne (3000); A OperationCanceledException exception is thrown when a request to cancel is received, which results in a task. The iscanceled value changes to TRUE//the code here is equivalent to _cts.
Token.throwifcancellationrequested (); if (_cts. iscancellationrequested) throw new OperationCanceledException (_cts.
Token); }, NULL,//context object, task. AsyncState can get to this object, and the CTX above can also get this object _cts.
Token//Associated CancellationToken object for canceling an operation); Start task tasks.
Start (); Task. Wait ();
Wait for the task to finish on the current thread lblmsg.text = "performed a task with no return value, execution completed in 3 seconds"; Processing of a task after execution (note: The ContinueWith method supports any callback, that is, multiple tasks can be written.) ContinueWith () will be recalled) task. ContinueWith (CTX) => the method {if (CTX) that is called after the task has finished executing. iscanceled)//task cancelled {var ignored = Dispatcher.runasync (coredispatcherpriorit Y.high, () => {Lblmsg.text = =
Environment.NewLine;
Lblmsg.text + = "Cancels the execution of a task with no return value";
}); } if (CTX. isfaulted)//task has an unhandled exception {var ignored = Dispatcher.runasync (coredispatcherp Riority. High, () => {lblmsg.text + = En Vironment.
newline;
Lblmsg.text + = "" Perform a task with no return value "An unhandled exception has occurred";
}); } if (CTX. iscompleted)//The task is completed (the task is successfully executed or canceled or an unhandled exception will be CTX.) IsCompleted = = true) {var ignored = Dispatcher.runasync (coredispatcherpriorit Y.high, () => {Lblmsg.text = =
Environment.NewLine; Lblmsg.text + = "Perform a task with no return value" execution completed, TaskId: "+ ctx."
Id.tostring ();
});
}
});
} private void Btncanceltask_click_1 (object sender, RoutedEventArgs e) {//Request to cancel operation _cts.
Cancel (); _cts. Cancelafter (1000); Request to cancel after 1000 milliseconds} private void Btncreatetaskwithreturn_click_1 (object sender, Routedev
Entargs e) {_cts = new CancellationTokenSource (); Func<object, String> handler = Delegate (object state)//State is the transitive context object {//blocks 3000 milliseconds on the current thread (signals when a cancellation request is received, stops blocking) _cts.
Token.WaitHandle.WaitOne (3000); A OperationCanceledException exception is thrown when a request to cancel is received, which results in a task. The iscanceled value changes to TRUE//the code here is equivalent to _cts.
Token.throwifcancellationrequested (); if (_cts. iscancellationrequested) throw new OperationCanceledException (_cts.
Token);
Return "I am" to perform a returned value of a task with a return value ";
}; Task.Factory.StartNew ()-Creates a task and executes it immediately, at any time through a task. Status Get task status//Task.run () also create task and execute task<string> task immediately = task.factory.startnew<string > (handler,//task called method, with return value NULL,//context object, task. AsyncState can get to this object _cts.
Token//Associated CancellationToken object for canceling an operation);
Lblmsg.text = "performed a task with a return value, completed in 3 seconds"; Processing of a task after execution (note: The ContinueWith method supports any callback, that is, multiple tasks can be written.) ContinueWith () arewill be recalled) task. ContinueWith (CTX) => {if (ctx. iscanceled)//task cancelled {var ignored = Dispatcher.runasync (coredispatcherpriorit Y.high, () => {Lblmsg.text = =
Environment.NewLine;
Lblmsg.text + = "Cancels the execution of a task with a return value";
}); } if (CTX. isfaulted)//task has an unhandled exception {var ignored = Dispatcher.runasync (coredispatcherp Riority. High, () => {lblmsg.text + = En Vironment.
newline;
Lblmsg.text + = "" Perform a task with return value "An unhandled exception has occurred";
}); } if (CTX. IsCompleted//Task completed (the task was successfully executed or canceled or an unhandled exception occurred) cTx. IsCompleted = = true) {var ignored = Dispatcher.runasync (coredispatcherpriorit Y.high, () => {Lblmsg.text = =
Environment.NewLine; Lblmsg.text + = "Perform a task with return value" execution completed, TaskId: "+ ctx."
Id.tostring ();
}); The return value of the output task if (!CTX) when the task completes successfully. Iscanceled &&!ctx. isfaulted) {ignored = Dispatcher.runasync (coredispatcherpriority.high , () => {lblmsg.text + = Enviro Nment.
newline; The return value of the task Lblmsg.text + = CTX.
result;
});
}
}
}); } private void Btncanceltaskwithreturn_click_1 (object sender, RoutedEventArgs e) {//Request to cancel Operation _ct
S.cancel (); _cts. Cancelafter (1000); Request to cancel operation after 1000 milliseconds}}