首页 > 编程语言 > 详细

多线程协作 FileStream文件读写操作,读写冲突解决

时间:2016-01-10 12:59:35      阅读:134      评论:0      收藏:0      [点我收藏+]
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 = 0;
        static void Main(string[] args)
        {
            int[] aa = new int[3] { 1, 2, 3 };
            for (int i = 1; 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, 0, 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=  1; i<=15; 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 1:
                    BasePath += "\\aa.txt";
                    break;
                case 2:
                    BasePath += "\\bb.txt";
                    break;
                case 3:
                    BasePath += "\\cc.txt";
                    break;
            }
            lock(new object())
            {
                StreamWriter sw = new StreamWriter(BasePath);
                int start = (i - 1) * 5 + 1;
                int end = i * 5;
                for (int j = start; j <= end; j++)
                {
                    sw.WriteLine(j);
                }

                sw.Close();
                i++;
                if (i >= 3)
                {

                    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, 0, bs.Length);
                        sw1.Flush();
                        sw1.Close();
                    }
                    ///出现异常说明也有另外的进程在操作该文件,睡眠500毫秒,再试机写入内容
                    catch (Exception ex)
                    {

                        Thread.Sleep(500);
                    }
                }
            }
        }
    }
}

 

多线程协作 FileStream文件读写操作,读写冲突解决

原文:http://www.cnblogs.com/kexb/p/5118133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!