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
How about this?
TextWriter.Synchronized(myWriter).WriteLine("Hello World!!!");
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With