.NET 线程同步(2)

<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
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().
11AJ20TF440I.jpg
seover="window.status='正文--.NET 线程同步(2)';return true">
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
阅读更多
文章标签: .net thread system class
个人分类: .net
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭