如何将行写入文本文件线程安全 - 多线程

时间:2013-03-02 12:17:10

标签: c# multithreading file-io thread-safety streamwriter

我刚尝试了这个,但它失败了

public MainWindow()
{
    InitializeComponent();
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{

    Task.Factory.StartNew(() =>
    {
        writeFile();
    });

}

TextWriter myWriter = new StreamWriter("deneme.txt");

void writeFile()
{
    for (int k = 0; k < 10000; k++)
    {
        int irTempPara = k;
        Task.Factory.StartNew(() =>
        {
            writeFileForReal(irTempPara);
        });
        System.Threading.Thread.Sleep(10);
    }
}

void writeFileForReal(int srParameter)
{
    for (int k = 0; k < 999999999; k++)
    {
        myWriter.WriteLineAsync(srParameter + "_" + k);
    }
}

这是c#4.5 WPF应用程序

那么你建议用什么方法将行写入文本文件最有效和多线程

4 个答案:

答案 0 :(得分:16)

这个怎么样?

TextWriter.Synchronized(myWriter).WriteLine("Hello World!!!");

答案 1 :(得分:2)

你可以像你一样使用简单的TPL方式,但你可以设置:

    void writeFile()
    {
        for (int k = 0; k < 10000; k++)
        {
            int irTempPara = k;
            Task.Factory.StartNew(() =>
            {
                writeFileForReal(irTempPara);
            }, TaskCreationOptions.LongRunning); // this way you do not need sleep
            // System.Threading.Thread.Sleep(10);
        }
    }

http://coderkarl.wordpress.com/2012/12/13/long-running-tasks-and-threads/

答案 2 :(得分:1)

在多线程中,您绝不能依赖Sleep进行同步。相反,请考虑使用同步机制,例如semaphoremutex

答案 3 :(得分:1)

我们可以使用ReaderWriterLockSlim http://www.johandorper.com/log/thread-safe-file-writing-csharp

private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();

public void WriteToFile(string text, string path) 
{
    _readWriteLock.EnterWriteLock();
    using (StreamWriter sw = new StreamWriter(path, true))
    {
        sw.WriteLine(text);
        sw.Close();
    }
    _readWriteLock.ExitWriteLock();
}