Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write lines to a text file thread safe - multi threading

I just tried this and it failed

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

It is c# 4.5 WPF application

So what method would you suggest for writing lines to a text file most effeciently and multi threading

like image 841
MonsterMMORPG Avatar asked Nov 30 '22 21:11

MonsterMMORPG


2 Answers

How about this?

TextWriter.Synchronized(myWriter).WriteLine("Hello World!!!");
like image 138
ZZZ Avatar answered Dec 04 '22 03:12

ZZZ


You can just use simple TPL way as you do, but you can set:

    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/

like image 32
hackp0int Avatar answered Dec 04 '22 01:12

hackp0int