多线程的实现方法,并无实际读写实例,参考过程中可以在相应地方加以修改。具体代码如下:
/************************************
* Author:Kim
* Date:2013.6.11
************************************/using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;namespace Thread
{
class Program
{const int T = 10; //总线程数
const int LOCK = 1000; //申请读写时间
const int SLEEP = 100; //线程挂起时间static FileStream fs = new FileStream("E:\\test.txt", FileMode.OpenOrCreate);
static Thread[] threadTest = new Thread[T];
static ReaderWriterLock readWriteLock = new ReaderWriterLock();static void Main(string[] args)
{
Initial();
for (int i = 0; i < T; i++)
{
threadTest[i].Start();
}
for (int i = 0; i < T; i++)
if (threadTest[i].IsAlive)
threadTest[i].Abort();
Pause();
}static void Pause()
{
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}static void Initial() //随机初始化线程读写状态
{
for (int i = 0; i < T; i++)
{Random rd = new Random();
int j = rd.Next(2);if (j == 0)
{
Console.WriteLine("Thread" + i.ToString() + " is to read.");
threadTest[i] = new Thread(new ThreadStart(ReadTest));
}
else
{
Console.WriteLine("Thread" + i.ToString() + " is to write.");
threadTest[i] = new Thread(new ThreadStart(WriteTest));
}
}
}static void ReadTest() //读取文件
{
try
{
readWriteLock.AcquireReaderLock(LOCK);
StreamReader rd = new StreamReader(fs);
Console.WriteLine("Reading...");
Thread.Sleep(SLEEP);
rd.Close();
readWriteLock.ReleaseReaderLock();
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
}static void WriteTest() //写入文件
{
try
{
readWriteLock.AcquireWriterLock(LOCK);
StreamWriter wr = new StreamWriter(fs);
Console.WriteLine("Writing...");
Thread.Sleep(SLEEP);
wr.Close();
readWriteLock.ReleaseWriterLock();
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
}}
}