C#多线程读写文件的实现方法

多线程的实现方法,并无实际读写实例,参考过程中可以在相应地方加以修改。具体代码如下:

/************************************
* 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);
}
}

}
}

转载于:https://www.cnblogs.com/muurf/archive/2013/06/14/3135256.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值