FileStream locking a file for reading and writing

不想你离开。 提交于 2019-12-01 05:15:39
xagyg

The FileShare.None flag does not cause threads to queue, it just locks the file, hence the exception that you get. To provide mutually exclusive access you can lock a shared object prior to writing.

But you say this "Now my program is a multithreaded application. Any thread could be trying to write to this file." Now, do these threads all use exactly the same method to write to the file? Let's assume they do, then this should work ...

Create a static class variable ...

private static object lockObject = new object();

Use it here ...

lock (lockObject) 
{
    using(var sw = new StreamWriter(fs))
    {
       sw.Write(str + text);
    }
}

I have made some assumptions about the threads, so you may have to look up info on synchronization if this doesn't work or provide some more info to us.

Also, please close your StreamReader earlier (in case the method returns earlier). Close it immediately after you use it or better yet use using.

Damitha

Try Thread Synchronization. You can find more details from this link.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!