Performing asynchronous tasks using task parallel libraries The following example shows how to create and use a task object by calling the Taskfactory.startnew method.
1 usingSystem;2 usingSystem.Threading;3 usingSystem.Threading.Tasks;4 5 classExample6{7 Static voidMain ()8{9action<Object> action = (Objectobj) =Ten{ OneConsole.WriteLine ("task={0}, Obj={1}, thread={2}", ATask.currentid, obj, -THREAD.CURRENTTHREAD.MANAGEDTHREADID); -}; the - //Create a task but does not start it. -Task T1 =NewTask (Action, "Alpha"); - + //Construct a started task -Task t2 = Task.Factory.StartNew (Action, "Beta"); + //Block The main thread to demonstate this t2 is executing AT2. Wait (); at - //Launch T1 -T1. Start (); -Console.WriteLine ("T1 has been launched. (Main thread={0})", -THREAD.CURRENTTHREAD.MANAGEDTHREADID); - //Wait for the task to finish. inT1. Wait (); - to //Construct a started task using Task.run. +String Taskdata = "Delta"; -Task t3 = Task.run (() = the{ *Console.WriteLine ("task={0}, Obj={1}, thread={2}", $Task.currentid, Taskdata,Panax NotoginsengTHREAD.CURRENTTHREAD.MANAGEDTHREADID); -}); the //Wait for the task to finish. +T3. Wait (); A the //Construct an unstarted task +Task T4 =NewTask (Action, "Gamma"); - //Run it synchronously $T4. RunSynchronously (); $ //Although the task was run synchronously, it's a good practice - //To wait for it in the event exceptions were thrown by the task. -T4. Wait (); the} -}Wuyi //The example displays output like the following: the //Task=1, Obj=beta, thread=3 - //T1 has been launched. (Main thread=1) Wu //task=2, Obj=alpha, thread=4 - //Task=3, Obj=delta, thread=3 About //Task=4, Obj=gamma, thread=1 $ View Code
. NET parallel computing and concurrent 7-task Async