MonsterMMORPG MonsterMMORPG - 25 days ago 6
C# Question

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

ZZZ ZZZ
Answer Source

How about this?

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