Multi-thread thread synchronization: Lock, Monitor, interlocked, Mutex, ReaderWriterLock
Introduced
Re-visualize the thread sync for Windows 8 Store Apps
Lock-is actually a encapsulation of the Monitor.Enter () and Monitor.Exit ()
Monitor-Lock
Interlocked-provides atomic operations for numeric variables shared by multiple threads
Mutex-mutexes, primarily for mutexes across processes within the same system
ReaderWriterLock-Read and write lock
Example
1, the use of the demo lock
Thread/lock/lockdemo.xaml
<page
x:class= "XamlDemo.Thread.Lock.LockDemo"
xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
xmlns:local=" using: XamlDemo.Thread.Lock "
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=" lblmsgwithoutlock "
fontsize=" 14.667 "/> <textblock name= lblmsgwithlock" fontsize= "14.667"/>
</StackPanel>
</ Grid>
</Page>
Thread/lock/lockdemo.xaml.cs
* * Demo Lock Usage * Note: Lock is actually a package for Monitor.Enter () and Monitor.Exit ()/using System.Collections.Generic;
Using System.Threading.Tasks;
Using Windows.UI.Xaml.Controls;
Using Windows.UI.Xaml.Navigation; Namespace XamlDemo.Thread.Lock {public sealed partial class Lockdemo:page {//need to Lock object pri
vate static readonly Object _objlock = new Object ();
private static int _countwithoutlock;
private static int _countwithlock; Public Lockdemo () {this.
InitializeComponent (); } protected async override void Onnavigatedto (NavigationEventArgs e) {list<task> T
asks = new list<task> ();
A total of 100 tasks are executed in parallel with each task accumulating the same static variable 100,000 times to simulate concurrent access to static variables for (int i = 0; i < i++) { Task task = Task.run (() => {/************** Have a lockThe logic starts ******************/try {//Lock the specified by lock
object to obtain the exclusive lock, releasing the exclusive lock after the code in the lock area has finished executing, and the other threads entering this queue wait for lock (_objlock) before the lock is released.
{for (int j = 0; J < 100000; J + +) {
_countwithlock++; }} finally {}/***
The logical end of a lock ******************//****************** logic begins ******************/ for (int j = 0; J < 100000; J + +) {_countwi
thoutlock++;
/****************** logical End ******************/}); Tasks.
ADD (Task);
} Wait for all tasks to complete await task.whenall (tasks);
Lblmsgwithoutlock.text = "counter (without lock) Result:" + _countwithoutlock.tostring ();
Lblmsgwithlock.text = "counter (with Lock) Result:" + _countwithlock.tostring (); }
}
}