写入文件的两个流

时间:2017-04-26 13:39:37

标签: c# multithreading synchronization filestream

当写入从一个文件开始到结果文件时,条目通过,并且从第二个文件到该结果文件被阻止。所以在两个流中记录不能同时可用。错误:进程无法访问文件,因为此文件正由另一个进程使用。我如何解决这个问题。我尝试了不同的方法。例如,如果直接写入两个流中的文件,但是将字符串添加到某个数组,然后最后通过该数组并将所有内容写入文件。它必须没有同步。

class Program
{
    public static void WriteOneThread()
    {
        List<char> listOfChars = new List<char>();
        FileInfo file = new FileInfo(@"C:\test\task.txt");
        FileStream stream = file.Open(FileMode.Open, FileAccess.ReadWrite);
        StreamReader reader = new StreamReader(stream);
        string str = reader.ReadToEnd();

        Console.WriteLine(str);

        char[] arr = str.ToCharArray();
        for (int i = 0; i < arr.Length; i++)
        {
            listOfChars.Add(arr[i]);
        }
        Console.WriteLine(new string('-', 20));
        FileInfo file2 = new FileInfo(@"C:\test\Result.txt");
        try
        {
            foreach (var value in listOfChars)
            {
                StreamWriter writer = file2.CreateText();
                writer.WriteLine(value);
                writer.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }        
}
    public static void WriteSecondThread()
    {
        List<char> listOfChars = new List<char>();
        FileInfo file = new FileInfo(@"C:\test\pretask.txt");
        FileStream stream = file.Open(FileMode.Open, FileAccess.ReadWrite);
        StreamReader reader = new StreamReader(stream);
        string str = reader.ReadToEnd();

        Console.WriteLine(str);

        char[] arr = str.ToCharArray();
        for (int i = 0; i < arr.Length; i++)
        {
            listOfChars.Add(arr[i]);
        }
        Console.WriteLine(new string('-', 20));
        FileInfo file2 = new FileInfo(@"C:\test\Result.txt");
        try
        {
            foreach (var value in listOfChars)
            {
                StreamWriter writer = file2.CreateText();
                writer.WriteLine(value);
                writer.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }      
}
    static void Main(string[] args)
    {
        Thread threadOne = new Thread(WriteOneThread);
        Thread threadSecond = new Thread(WriteSecondThread);

        threadOne.Start();
        Thread.Sleep(10000);
        threadSecond.Start();

        threadOne.Join();
        threadSecond.Join();

        Console.WriteLine("Запись в файл осуществлена");
        Console.ReadKey();
    }
}

0 个答案:

没有答案