.NET线程同步(3)

来源:互联网 发布:淘宝爱逛街报名入口 编辑:程序博客网 时间:2024/05/16 23:40
<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>
另一个同步策略是手控技术,System.Threading命名空间中的一些可以用于手控同步的类。ManualResetEvent类用来使线程处于等待状态,它有2种状态:有信号(True)或无信号(False)。还有2个重要方法:Reset()和Set()。

下面代码说明Reset()方法的用法:

using System;
using System.Threading;

namespace ManualReset
{

class Reset
{

[STAThread]
static void Main()
{
ManualResetEvent manRE;
manRE=new ManualResetEvent(true); // 赋给信号量
bool state=manRE.WaitOne(1000,true);
Console.WriteLine("ManualResetEvent After first waitone "+state);

manRE.Reset(); //设置ManualResetEvent状态为无信号量
state=manRE.WaitOne(5000,true);
Console.WriteLine("ManualResetEvent After second waitone "+state);
}
}
}

运行结果:



下面代码说明Set()方法的用法:

using System;
using System.Threading;
namespace ManualSet
{

class Set
{

[STAThread]
static void Main(string[] args)
{
ManualResetEvent manRE;
manRE=new ManualResetEvent(false);
Console.WriteLine("Before waitone");
bool state=manRE.WaitOne(5000,true);
Console.WriteLine("ManualResetEvent After first waitone "+state);

manRE.Set(); //将其状态设为有信号量
Thread.Sleep(3000);
state=manRE.WaitOne(5000,true);
Console.WriteLine("ManualResetEvent After second waitone "+state);
}
}
}

运行结果:


<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>
原创粉丝点击