private int interLocked = 9;
private int lockInt = 19;
private object lockObj = new object();
private Mutex mutex;
private Semaphore semaphore = new Semaphore(2,2);
public MainPage()
{
this.InitializeComponent();
}
protected override voidOnNavigatedTo(NavigationEventArgs e)
{
//線程同步:Interlocked
ThreadPool.RunAsync(
(source) =>
{
Interlocked.Increment(ref interLocked);
//Interlocked.Decrement(ref interLocked);
},
WorkItemPriority.Normal);
//lock
ThreadPool.RunAsync(
(source) =>
{
lock (lockObj)
{
lockInt++;
lockInt *=5;
}
},
WorkItemPriority.Normal);
//Monitor
ThreadPool.RunAsync(
(source) =>
{
Monitor.Enter(lockObj);
Monitor.Wait(lockObj);//釋放對象上的鎖并進入對象的等待隊列
//Monitor.Pulse(lockObj);//通知等待隊列中的線程鎖定對象狀態(tài)的更改
Monitor.Exit(lockObj);//釋放指定對象上的鎖
},
WorkItemPriority.Normal);
//Mutex
ThreadPool.RunAsync(
(source) =>
{
bool isNotRunning;
mutex = new Mutex(true, "MSI-Muxtex", outisNotRunning);
if (!isNotRunning)
{
//DoSomething ...
}
},
WorkItemPriority.Normal);
//Semaphore
ThreadPool.RunAsync(
(source) =>
{
//阻止當前線程,直到當前WaitHandle收到信號
semaphore.WaitOne();
//退出信號量并返回前一個計數(shù)
semaphore.Release();
},
WorkItemPriority.Normal);
//AutoResetEvent autoRestEvent = new AutoResetEvent(false);
//autoRestEvent.Set();
//ManualResetEvent manualRestEvent = newManualResetEvent(false);
//manualRestEvent.Set();
//manualRestEvent.Reset();
EventWaitHandle eventWaitHandle = new EventWaitHandle(false,EventResetMode.AutoReset, "msiEventWaitHandle");
eventWaitHandle.WaitOne();
eventWaitHandle.Set();
eventWaitHandle.Reset();
}