For 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, perhaps dozens of times, and should run asynchronously.
So I tried calling the method in a new thread like this (where writer is the class in which WriteToFile lives)
//in a loop... Thread thread = new Thread( writer.WriteToFile ); thread.Start( );
Which works fine once, but throws an IO exception that the file is used by another process in subsequent iterations. Which really makes sense, actually, but I don't know how to get around this.
I tried using Join () like this
Thread thread = new Thread( writer.WriteToFile ); thread.Start( ); thread.Join();
But this blocks the calling thread until all the merged threads have completed, what kind of target hit is not?
I tried using ThreadPool.QueueUserWorkItem(writer.WriteToFile); but getting the same IO exception.
I tried to use lock
private object locker = new object(); public void WriteToFile( ) { lock(locker){
But it had no visible effect.
I also tried using the Task class to no avail.
So, how can I βstackβ these background streams for writing to a single file without conflicts without blocking the calling stream?