当前位置:首页>>ASP.NET教程>>Asp.NET综合技巧>>.NET线程同步(1)
.NET线程同步(1)
2009/11/8 13:19:18
在处理.net线程同步问题,有许多办法,这里所将谈到的是特定代码区的同步.

这些特定的代码区是方法中重要的代码段,他们可以改变对象的状态,或者更新另一个资源.


Monitor类用于同步代码去,其方式是使用Monitor.Enter()方法获得一个锁,然后使用Monitor.Exit()方法释放该锁.

示例如下:

using System;
using System.Threading;

namespace EnterExit
{
public class EnterExit
{
private int result=0;
public EnterExit()
{
}

public void NonCriticalSection()
{
Console.WriteLine("Enter Threah"+Thread.CurrentThread.GetHashCode());
for(int i=1;i<=5;i++)
{
Console.WriteLine("Result="+result++ +" ThreadID"+Thread.CurrentThread.GetHashCode());
Thread.Sleep(1000);
}
Console.WriteLine("Exiting Threah"+Thread.CurrentThread.GetHashCode());
}

public void CriticalSection()
{
Monitor.Enter(this);
Console.WriteLine("Enter Threah"+Thread.CurrentThread.GetHashCode());
for(int i=1;i<=5;i++)
{
Console.WriteLine("Result="+result++ +" ThreadID"+Thread.CurrentThread.GetHashCode());
Thread.Sleep(1000);
}
Console.WriteLine("Exiting Threah"+Thread.CurrentThread.GetHashCode());
Monitor.Exit(this);
}

public static void Main(String[] args)
{

EnterExit e=new EnterExit();
if(args.Length>0)
{
Thread nt1=new Thread(new ThreadStart(e.NonCriticalSection));
nt1.Start();

Thread nt2=new Thread(new ThreadStart(e.NonCriticalSection));
nt2.Start();
}
else
{
Thread ct1=new Thread(new ThreadStart(e.CriticalSection));
ct1.Start();

Thread ct2=new Thread(new ThreadStart(e.CriticalSection));
ct2.Start();
}
}
}

}



运行结果:

Enter Threah 1

Result=0 Thread1

Result=1 Thread1

Result=2 Thread1

Result=3 Thread1

Result=4 Thread1

Exiting Thread1

Enter Threah 2

Result=5 Thread2

Result=6 Thread2

Result=7 Thread2

Result=8 Thread2

Result=9 Thread2

Exiting Thread2

[1]