1. Overview
This chapter includes synchronizing resources and canceling long-time task-related content.
2. Main content
2.1 Synchronizing Resources
①lock keyword implementation. will block the program, potentially causing a deadlock.
The ②volatile keyword disables compilation optimizations to avoid the effects of multithreading when optimizing code.
Private Static volatile int 0;
The ③interlocked keyword can be atomized with some simple numeric operations and a comparison substitution operation.
Interlocked.Increment (ref//interlocked.decrement (ref/ / Interlocked.exchange (ref1); interlocked. CompareExchange (ref value, NewValue, compareTo);
2.2 Canceling a task
①cancellationtoken
CancellationTokenSource CancellationTokenSource = NewCancellationTokenSource (); CancellationToken token=Cancellationtokensource.token; Task Task= Task.run (() = { while(!token. iscancellationrequested) {Console.Write ("*"); Thread.Sleep ( +); }}, token); Console.WriteLine ("Please enter to stop the task"); Console.ReadLine (); Cancellationtokensource.cancel ();
② use Task.waitany () to set the time-out period for a task.
Task longrunning = Task.run (() ={ thread.sleep (10000);}); int index = task.waitany (new); if (Index = =-1) Console.WriteLine ("");
3. Summary
When you ① a multithreaded environment to access shared data, consider avoiding data corruption and dirty reads.
② uses the LOCK keyword to enable multi-threaded sequential access to shared resources.
③ can use interlocked to achieve simple atomic manipulation.
④ can use the CancellationToken of the CancellationTokenSource class to control the cancellation task.
Chapter II Management of program flow (in. net4.5) Management multithreading