Given a method that writes to a text file
public void WriteToFile( ) {
var file = "C:\\AsyncTest.txt";
var writer = File.Exists( file ) ? File.AppendText( file ) : File.CreateText( file );
writer.WriteLine( "A simulated entry" );
writer.Close();
}
I need to simulate a scenario in which this method could be called in a loop, possibly dozens of times and must run asynchronously.
So I tried calling the method in a new thread like so (where writer is the class where WriteToFile lives)
//in a loop...
Thread thread = new Thread( writer.WriteToFile );
thread.Start( );
Which works perfectly once, but throws an IO Exception that the file is being used by another process on subsequent iterations. Which makes perfect sense, actually, but I don't know how to work around it.
I tried using Join() like this
Thread thread = new Thread( writer.WriteToFile );
thread.Start( );
thread.Join();
But that locks the calling thread until all the joined threads complete, which sort of defeats the purpose, no?
I tried using ThreadPool.QueueUserWorkItem(writer.WriteToFile);
, but get the same IO exception.
I tried using a lock
private object locker = new object();
public void WriteToFile( ) {
lock(locker){
//same code as above
}
}
But that had no apparent effect
I also tried using the Task class to no avail.
So how can I "stack up" these background threads to write to a single file without conflict, while not locking up the calling thread?