How to write in a single file with multiple threads?

后端 未结 3 806
忘掉有多难
忘掉有多难 2020-12-03 17:23

I am creating Windows Application in C# in which I want to write in multiple files with multiple threads. I am getting data from different ports and there is one file associ

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 18:13

    As mentioned in the comments, this is asking for trouble.

    So, you need to have a thread-safe writer class:

    public class FileWriter
    {
        private ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim();
        public void WriteData(/*....whatever */)
        {
            lock_.EnterWriteLock();
            try
            {
                // write your data here
            }
            finally
            {
                lock_.ExitWriteLock();
            }
        }
    
    } // eo class FileWriter
    

    This is suitable for being called by many threads. BUT, there's a caveat. There may well be lock contention. I used a ReadWriterLockSlim class, because you may want to do read locks as well and hell, that class allows you to upgrade from a read state also.

提交回复
热议问题