开发者

how to write to file in an multithreaded environment

I have a program that runs on multithread but all of them need to save results to same text file

I get access violation 开发者_如何学JAVAerror

how can i avoid doing that


Wrap file IO into a lock statement:

private static object _syncRoot = new object();

and then:

lock(_syncRoot)
{
    // do whatever you have to do with this file
}


Take a look at the lock statement: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx


The simplest is to simply make sure you have some locking construct (mutex, monitor, etc) against access to the file, then each thread can access it in isolation. This could either be accessing the same underlying Stream/TextWriter/etc, or could be opening/closing the file inside the locked region.

A more complex approach would be to have a dedicated writer thread, and a synchronised work queue. Then all threads can add to the queue and a single thread draughts and writes to the file. This means your main threads are only blocked while adding to a queue (very brief), rather than blocked on IO (slower). However, note that if the process exits abnormally, data in the queue may be lost.


I would recommend reading up on the ReaderWriterLock class or the ReaderWriterLockSlim class which is faster but has some gotchas, I believe it would suit your needs perfectly.

ReaderWriterLock
ReaderWriterLockSlim

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜