ResourceData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProcessTest
{
/// <summary>
/// 单例模式
/// </summary>
public class ResourceData
{
private static readonly ResourceData instance = new ResourceData();
static ResourceData()
{
}
private ResourceData()
{
}
public static ResourceData Instance
{
get
{
return instance;
}
}
public string DATA;
}
}
ResourceBLL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ProcessTest
{
public class ResourceBLL
{
static System.Threading.ReaderWriterLock rwl = new System.Threading.ReaderWriterLock();
public static string Read()
{
return ResourceData.Instance.DATA;
}
//写数据
public static void Write()
{
try
{
string value;
try
{
value = DateTime.Now.ToString();
}
catch (Exception)
{
//获取值时如果出现异常,则不改变选前的值
//log 同时应该记录到日志当中
return;
}
ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ThreadMethod);
Thread myThread = new Thread(ParStart);
object param = value;
myThread.Start(param);
}
catch (ApplicationException)
{
//获取写操作锁失败
//log 同时应该记录到日志当中
}
}
public static void ThreadMethod(object ParObject)
{
//Timeout.Infinite 无限延长等待时间
rwl.AcquireWriterLock(Timeout.Infinite);
//Thread.Sleep(1000);测试
ResourceData.Instance.DATA = ParObject as string ;
Console.WriteLine("W:{0}", ParObject);
rwl.ReleaseWriterLock();
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ProcessTest
{
class Program
{
static void Main(string[] args)
{
ResourceBLL.Write();
//分别创建2个读操作线程,2个写操作线程,并启动
Thread tr0 = new Thread(new ThreadStart(Read));
Thread tr1 = new Thread(new ThreadStart(Read));
Thread tr2 = new Thread(new ThreadStart(Write));
Thread tr3 = new Thread(new ThreadStart(Write));
tr0.Start();
tr1.Start();
tr2.Start();
tr3.Start();
//等待线程执行完毕
tr0.Join();
tr1.Join();
tr2.Join();
tr3.Join();
Console.WriteLine("1");
System.Console.ReadKey();
}
//读数据
static void Read()
{
var length = 50000000;
for (int i = 0; i < length; i++)
{
//Thread.Sleep(20);
//ResourceBLL.Read();
Console.WriteLine("R:{0}", ResourceBLL.Read());
}
}
//写数据
static void Write()
{
var length = 10000000;
for (int i = 0; i < length; i++)
{
Thread.Sleep(500);
ResourceBLL.Write();
}
}
}
}