程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#線程資源同步方式總結(2)

C#線程資源同步方式總結(2)

編輯:關於C語言
.使用lock關鍵字

地球人都知道,使用lock關鍵字可以獲取一個對象的獨占權,任何需要獲取這個對象的操作的線程必須等待以獲取該對象的線程釋放獨占權,lock提供了簡單的同步資源的方法,與Java中的synchronized關鍵字類似。

lock關鍵字的使用示例代碼如下

object o = new object();
lock (o)
{
Console.WriteLine("O");
}

4.使用System.Theading.Monitor類進行同步

system.Threading.Monitor類提供了與lock類似的功能,不過與lock不同的是,它能更好的控制同步塊,當調用了Monitor的Enter(Object o)方法時,會獲取o的獨占權,直到調用Exit(Object o)方法時,才會釋放對o的獨占權,可以多次調用Enter(Object o)方法,只需要調用同樣次數的Exit(Object o)方法即可,Monitor類同時提供了TryEnter(Object o,[int])的一個重載方法,該方法嘗試獲取o對象的獨占權,當獲取獨占權失敗時,將返回false,查看如下代碼

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MonitorApplication
{
class Program
{
private static object m_monitorObject = new object();
static void Main(string[] args)
{
Thread thread = new Thread(Do);
thread.Name = "Thread1";
Thread thread2 = new Thread(Do);
thread2.Name = "Thread2";
thread.Start();
thread2.Start();
thread.Join();
thread2.Join();
}
static void Do()
{
if (!Monitor.TryEnter(m_monitorObject))
{
Console.WriteLine("Can't visit Object " + Thread.CurrentThread.Name);
return;
}
try
{
Monitor.Enter(m_monitorObject);
Console.WriteLine("Enter Monitor " + Thread.CurrentThread.Name);
Thread.Sleep(5000);
}
finally
{
Monitor.Exit(m_monitorObject);
}
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved