1 //Task Scheduler2TaskScheduler Uischeduler =NULL;3 PublicForm1 ()4 {5 //Get Task Scheduler6Uischeduler =Taskscheduler.fromcurrentsynchronizationcontext ();7 InitializeComponent ();8 }9 Ten Private voidBtntaskscheduler_click (Objectsender, EventArgs e) One { ASystem.Threading.CancellationTokenSource cts =NewSystem.Threading.CancellationTokenSource (); - //Start a task thread -task<int> t = Task.run (() =>sum ( -)); the //using the Uischeduler Scheduler to implement control access across threads -T.continuewith (task = Txtres.text =t.result.tostring (), CTS. Token,taskcontinuationoptions.onlyonrantocompletion,uischeduler); -T.continuewith (task = Txtres.text ="Error", System.Threading.CancellationToken.None, Taskcontinuationoptions.onlyonfaulted,uischeduler); - } + Private intSum (intnum) - { + intres =0; A for(inti =0; I <= num; i++) at { - checked{Res + =i;} - //res + = i; - } - returnRes; -}
Using the TaskScheduler Scheduler to implement control access across threads