当前位置:首页>>ASP.NET教程>>Asp.NET综合技巧>>.NET 线程同步(2)
.NET 线程同步(2)
2009/11/8 13:19:18
Monitor类的TryEnter()方法非常类似于Enter()方法,他试图获得对象的独占锁,不过它不会象Enter()方法那样暂停. 如果线程成功进入,则TryEnter()方法返回True.

TryEnter()有3种重载方法,其中两个都带有超时参数,表示等待锁定的时间.

using System;
using System.Threading;

namespace MonitorTryEnter
{
public class TryEnter
{
public TryEnter()
{
}

public void CriticalSection()
{
bool b=Monitor.TryEnter(this,1000);
Console.WriteLine("Thread "+Thread.CurrentThread.GetHashCode()+" TryEnter Value "+b);
for(int i=1;i<=3;i++)
{
Thread.Sleep(1000);
Console.WriteLine(i+" "+Thread.CurrentThread.GetHashCode()+" ");
}
Monitor.Exit(this);
}

public static void Main()
{
TryEnter a=new TryEnter();
Thread t1=new Thread(new ThreadStart(a.CriticalSection));
Thread t2=new Thread(new ThreadStart(a.CriticalSection));
t1.Start();
t2.Start();
}
}
}
运行结果:



在可能发生竞争,但不希望线程睡眠某个未指定的时间时,就可以使用TryEnter().

[1]