当前位置:萝卜系统下载站 > 技术开发教程 > 详细页面

.NET线程同步(1)

.NET线程同步(1)

更新时间:2022-06-26 文章作者:未知 信息来源:网络 阅读次数:

在处理.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

温馨提示:喜欢本站的话,请收藏一下本站!

本类教程下载

系统下载排行

网站地图xml | 网站地图html