多线程协作 FileStream文件读写操作,读写冲突解决
2024-10-19 05:54:52
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace ConsoleApplication8
{
/// <summary>
/// 本文的任务是通过多线程在三个文件aa.txt,bb.txt,cc.txt全部写入文件,完成任务之后,
/// 往ee.txt文件写入ok,之后主线程一直轮询去读取ee.txt该文件如果,里面出现ok,则往dd.txt写入内容,最后总任务完成之后删除临时文件ee.txt
/// </summary>
class Program
{
public static int i = ;
static void Main(string[] args)
{
int[] aa = new int[] { , , };
for (int i = ; i <=aa.Length; i++)
{
ParameterizedThreadStart ts = new ParameterizedThreadStart(ProcessData);
Thread th = new Thread(ts);
th.Start(i);
}
while (true)
{
string s = "";
FileStream fs = null;
try
{
fs = new FileStream(@"C:\Users\yiwannuofu\Desktop\\ee.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
}
///如果刚好也有人在操作该文件的时候,指的是有另外一进程在操作该文件,
/// 这里捕获异常继续尝试读取,直至成功,而对应的另一方或几方则睡眠500毫秒再尝试读取
catch (Exception ex)
{ Thread.Sleep(200);
continue;
} byte[] b = new byte[fs.Length];
fs.Read(b, , b.Length);
fs.Flush();
fs.Close(); s = Encoding.UTF8.GetString(b); if (s.Contains("ok"))
{
string BasePath = @"C:\Users\yiwannuofu\Desktop\dd.txt";
StreamWriter sw = new StreamWriter(BasePath);
for (int i= ; i<=; i++)
{
sw.WriteLine(i);
}
sw.Close();
File.Delete(@"C:\Users\yiwannuofu\Desktop\\ee.txt");
break;
}
}
Console.ReadKey(); } private static void ProcessData(object obj)
{
int i = Convert.ToInt32(obj);
string BasePath = @"C:\Users\yiwannuofu\Desktop"; switch (i)
{
case :
BasePath += "\\aa.txt";
break;
case :
BasePath += "\\bb.txt";
break;
case :
BasePath += "\\cc.txt";
break;
}
lock(new object())
{
StreamWriter sw = new StreamWriter(BasePath);
int start = (i - ) * + ;
int end = i * ;
for (int j = start; j <= end; j++)
{
sw.WriteLine(j);
} sw.Close();
i++;
if (i >= )
{ try
{
FileStream sw1 = new FileStream(@"C:\Users\yiwannuofu\Desktop\\ee.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
byte[] bs = Encoding.UTF8.GetBytes("ok".ToCharArray());
sw1.Write(bs, , bs.Length);
sw1.Flush();
sw1.Close();
}
///出现异常说明也有另外的进程在操作该文件,睡眠500毫秒,再试机写入内容
catch (Exception ex)
{ Thread.Sleep();
}
}
}
}
}
}
最新文章
- 读书笔记--SQL必知必会01--了解SQL
- Reorder array to construct the minimum number
- shell调试
- llvm學習(二)————llvm編譯與環境構建
- java 基本语法元素
- matlab图形矢量化解决方案
- crawler_爬虫开发的准备工作【工具】
- c++课程设计之通讯录电话簿管理设计
- 【转】使用virtualenv在ubuntu上搭建python 3开发环境
- git的撤销动作
- rpm和yum模拟安装
- 为什么matlab激活完后还要激活(Matlab2012b license失效解决办法)
- C++基础题--float型以整型格式输出
- ps和AI使用过程中的易错点整理
- MES方向准备
- 第一天:javascript实现界面运算及循环语句跳转语句
- C#,深入浅出全接触(一)
- php 批量修改文件格式或重命名
- Spring boot 使用的注解有哪些?
- 线程_synchronized_volatile_ReentranLock