1. Task (Tasks):
It is easy to invoke ThreadPool.QueueUserWorkItem to implement asynchronous operations, but this technique has many
. NET introduces task types to use tasks.
The following three methods are implemented asynchronously:
Public Static void Method () { = = Console.WriteLine ("")) ; // scheduling Tasks with start () New Task (() = Console.WriteLine ("")). Start (); // to dispatch a task by using the Run method Task.run (() = Console.WriteLine (""));
A. In order to create a task, you need to call the constructor and pass an Action or action<object> delegate. This delegate is the code action you want to perform.
B. If you call run, you can pass an action or fun<tresult> delegate. The two differences are that Aciton has no return value, fun has a return value
2. Wait for the task to complete and get the result:
Public Static voidMethod2 () {//Create a tasktask<int> t =Newtask<int> (n = Sum (int) n),Ten); //Start a taskT.start (); //wait for the task to completet.wait (); //Get ResultsConsole.WriteLine ("Sum is:{0}", T.result); } Private Static intSum (intN) {intsum =0; for(; n >0; n--) { checked{Sum + =N;} } returnsum; }
3. Cancel the task:
. NET Task (Task)