none
Access to file that being used by another thread / process / application RRS feed

  • Question

  • Hi.

    I created file to write there logs, but unfortunately there is many different threads that need to write there at the same time, so i get the usual exception that file being use by another process, how can i sidestep that problem? (it must to happen at parallel not in sequence).

    Thanks.

    Monday, April 21, 2014 2:58 PM

Answers

  • You cannot write to a single file in parallel unless you are writing to different sections of the file at the same time.  A log file wouldn't qualify for this.  Therefore you cannot write to the same file in parallel across multiple threads at the same time.  You will get garbage.

    If you need to write to a log from multiple threads then you should implement the writing in a standalone type (logger) that is thread safe and can be called by multiple threads.  This would require that your logger uses a sync object to ensure that it is writing to the file on only 1 thread at a time.  This can be done simply by using a lock statement if desired.  However every thread needs to use the same instance (or expose it as a static object) so that the lock will work correctly.

    Alternatively .NET already supports logging to a file using the Diagnostic framework as does most good logging infrastructures.

    Michael Taylor
    http://msmvps.com/blogs/p3net

    Monday, April 21, 2014 5:34 PM
    Moderator

All replies

  • AFAIK, i dont think FileSystem/FileStream supports concurrent writes. You may think about SQL compact which allows multiple threads to edit/read.

    Below is one thread having some explanation about q question similar to your one.

    http://stackoverflow.com/questions/3507770/write-to-a-file-from-multiple-threads-asynchronously-c-sharp

    Hope this helps... :)

    Monday, April 21, 2014 3:13 PM
  • You cannot write to a single file in parallel unless you are writing to different sections of the file at the same time.  A log file wouldn't qualify for this.  Therefore you cannot write to the same file in parallel across multiple threads at the same time.  You will get garbage.

    If you need to write to a log from multiple threads then you should implement the writing in a standalone type (logger) that is thread safe and can be called by multiple threads.  This would require that your logger uses a sync object to ensure that it is writing to the file on only 1 thread at a time.  This can be done simply by using a lock statement if desired.  However every thread needs to use the same instance (or expose it as a static object) so that the lock will work correctly.

    Alternatively .NET already supports logging to a file using the Diagnostic framework as does most good logging infrastructures.

    Michael Taylor
    http://msmvps.com/blogs/p3net

    Monday, April 21, 2014 5:34 PM
    Moderator