多线程锁读/写文本c#

时间:2017-02-02 17:53:49

标签: c# multithreading c#-4.0 thread-safety locking

经过大量的研究,在阅读并尝试了所有问题之后,我认为现在是时候寻求帮助了。

我在C#中有一个应用程序,我试图用不同的线程在SAME文件中写入。

public static void LaunchThreads(string path_file)
{
    int i = 0;
    Dictionary<int, Thread> threadsdico = new Dictionary<int, Thread>();
    while (i < MAX_THREAD)
    {
            Thread thread = new Thread(() => ThreadEntryWriter(string path_file));
            thread.Name = string.Format("ThreadsWriters{0}", i);
            threadsdico.Add(i, thread);
            thread.Start();
            i++;
    }
    int zz = 0;
    while (zz < threadsdico.Count())
    {
        threadsdico[zz].Join();
        zz++;
    }
}
private static readonly Object obj = new Object();
public static void ThreadEntryWriter(string path_file)
{
    int w = 0;
    while (w < 99)
    {       
        string newline = w + " - test" + "\r";
        lock(obj)
        {
            string txt = File.ReadAllText(path_file);
            using (TextWriter myWriter = new StreamWriter(path_file))
            {   
                TextWriter.Synchronized(myWriter).Write(txt + newline);
            }
        }
        w++;
    }
}

我尝试过所有内容,我的代码就像全球一样,但是我已经尝试过每一个方法,每个锁,每个文件都打开方法,但我一直在The process cannot access the files because it's in use。生成此错误的行是using (TextWriter myWriter = new StreamWriter(path_file))

我尝试了很多东西,关闭文件等,但是当线程同时开始工作时,程序停止并给我错误The process cannot access the files because it's in use(自我解释)。但我不明白为什么,锁定是为了阻止另一个线程进入这里。我使用Synchronized方法编写线程安全的。很抱歉长篇大论,这是我在这里的第一篇文章。

3 个答案:

答案 0 :(得分:0)

同步作者仍应处理:

var newline = w + " - test";
using (var sw = new StreamWriter(path_file))
using (var sync = TextWriter.Synchronized(sw))
{
    // no need to add a new line char, just use other method to write
    sync.WriteLine(txt + newline);
}

此外,您可以保存sync变量并从所有线程调用它的方法,它将为您完成所有工作,并且您可以在写完所有文本后稍后处理它。

答案 1 :(得分:0)

我测试你的代码并应用了一些更改,它运行正常,没有错误。

我使用winform应用程序来运行你的代码。请检查下面的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication14
{
    public partial class Form1 : Form
    {
        private readonly Object obj = new Object();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            LaunchThreads("D:\\log.txt");
        }

        public void LaunchThreads(string path_file)
        {
            int i = 0;
            int MAX_THREAD = 10;
            Dictionary<int, Thread> threadsdico = new Dictionary<int, Thread>();
            while (i < MAX_THREAD)
            {
                Thread thread = new Thread(() => ThreadEntryWriter(path_file, string.Format("ThreadsWriters{0}", i)));
                    thread.Name = string.Format("ThreadsWriters{0}", i);
                    threadsdico.Add(i, thread);
                    thread.Start();
                    i++;
            }
            int zz = 0;
            while (zz < threadsdico.Count())
            {
                threadsdico[zz].Join();
                zz++;
            }
        }

        public void ThreadEntryWriter(string path_file,string threadName)
        {
            int w = 0;
            while (w < 99)
            {
                string newline = w + " - test" + " Thread:" + threadName + "\r\n";
                lock (obj)
                {
                    string txt = File.ReadAllText(path_file);
                    using (TextWriter myWriter = new StreamWriter(path_file))
                    {
                        TextWriter.Synchronized(myWriter).Write(txt + newline);
                    }
                }
                w++;
            }
        }
    }
}

我输出如下。

  • 0 - 测试线程:ThreadsWriters1
  • 0 - 测试线程:ThreadsWriters2
  • 1 - 测试线程:ThreadsWriters2
  • 2 - 测试线程:ThreadsWriters2
  • 1 - 测试线程:ThreadsWriters1
  • ....
  • ....

答案 2 :(得分:0)

似乎您想从多个线程将行写入同一文件。

每次要输出一行然后追加一行并将其写出时,读取所有行的效率很低。

我认为导致错误的原因是您没有处置Synchronized TextWriter,因此即使处置了基础的TextWriter,它也可能始终保持对文件的引用打开。

使用您自己的锁定和同步TextWriter也是多余的。

我对您的代码做了一些更改,以共享一个Synchronized TextWriter,并且仅追加行,而不是读取整个文件,然后追加然后将其写出:

    public static void LaunchThreads(string path_file)
    {
        int i = 0;
        using(var sw = File.CreateText(path_file))
        using(var syncWriter = TextWriter.Synchronized(sw)) 
        {
            Dictionary<int, Thread> threadsdico = new Dictionary<int, Thread>();
            while (i < MAX_THREAD)
            {
                Thread thread = new Thread(() => ThreadEntryWriter(syncWriter));
                thread.Name = string.Format("ThreadsWriters{0}", i);
                threadsdico.Add(i, thread);
                thread.Start();
                i++;
            }
            int zz = 0;
            while (zz < threadsdico.Count())
            {
                threadsdico[zz].Join();
                zz++;
            }
        }
    }

    public static void ThreadEntryWriter(TextWriter writer)
    {
        int w = 0;
        while (w < 99)
        {       
            writer.WriteLine($"{w} - test");
            w++;
        }
    }