Im using the following to empty a txt file:
System.IO.File.WriteAllText(path, string.Empty);
The problem becomes when i run to many threads at once and they try to access the file at the same time..
Any ideas on an easy fix? :)
Im using the following to empty a txt file:
System.IO.File.WriteAllText(path, string.Empty);
The problem becomes when i run to many threads at once and they try to access the file at the same time..
Any ideas on an easy fix? :)
Multi-threading to the rescue!
You should use a Monitor
, AutoResetEvent
or lock
block (actually it's a Monitor) in order to synchronize access to the whole file.
public class SomeClass
{
private readonly static object _sync = new object();
public void WriteAllText()
{
lock(_sync)
{
File.WriteAllText("myfile.txt", "Hello world from a synchronized file access!!!");
}
}
}
}
This way you're preventing multiple threads to access the same file at the same time.
Learn about lock
block here:
http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.110).aspx
You should probably look into FileStream
. There's a good example of what you're trying to do here.
Another approach I would consider is to have a single writer thread serviced by a queue. All other threads that want to write to the file do this by adding text items to the end of the queue. The writer thread removes text items from the front of the queue and writes them to the file. You use the lock statement to synchronise access to the queue object, and a AutoResetEvent object to signal the writer thread when you add stuff to the queue, to let it know that there is something in the queue for it to process.