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();
}
}
}
}
}
}

最新文章

  1. 读书笔记--SQL必知必会01--了解SQL
  2. Reorder array to construct the minimum number
  3. shell调试
  4. llvm學習(二)————llvm編譯與環境構建
  5. java 基本语法元素
  6. matlab图形矢量化解决方案
  7. crawler_爬虫开发的准备工作【工具】
  8. c++课程设计之通讯录电话簿管理设计
  9. 【转】使用virtualenv在ubuntu上搭建python 3开发环境
  10. git的撤销动作
  11. rpm和yum模拟安装
  12. 为什么matlab激活完后还要激活(Matlab2012b license失效解决办法)
  13. C++基础题--float型以整型格式输出
  14. ps和AI使用过程中的易错点整理
  15. MES方向准备
  16. 第一天:javascript实现界面运算及循环语句跳转语句
  17. C#,深入浅出全接触(一)
  18. php 批量修改文件格式或重命名
  19. Spring boot 使用的注解有哪些?
  20. 线程_synchronized_volatile_ReentranLock

热门文章

  1. 剑指offer-第四章解决面试题思路(判断一个数组是否为二叉搜索树的后序遍历序列)
  2. Google搜索被屏蔽,如何使用Google搜索
  3. Linux IO 监控与深入分析
  4. mysql链接出现10060
  5. 机器人操作系统(ROS)教程22:ROS的3D可视化工具—rviz
  6. erlang的tcp服务器模板
  7. FPGA热设计
  8. jetty中war包解压路径
  9. 010. VS2015创建MVC项目
  10. platform驱动之probe函数