开发者

Cannot access a file in multi-thread

开发者 https://www.devze.com 2023-02-13 04:05 出处:网络
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None)) { using (StreamWriter sw = new StreamWriter(fs))
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None))
{
    using (StreamWriter sw = new StreamWriter(fs))
    {
        sw.WriteLine(DateTime.Now.ToString());  
           // multiple sw.WriteLine
    }
}

In spite of the fact that FileSh开发者_Go百科are is set to "None", an Exception is launched "The process cannot access the file because it is being used by another process.

I'm in Multi-thread context and the file is not written/read somewhere else.

Why ?


FileShare.None is saying "Don't let anybody share this file" - the opposite of what you want. I believe you were after FileShare.ReadWrite.

That being said, I recommend avoiding this issue altogether. It would be much better to have your writing handled in a single thread, and use a producer/consumer approach to requesting an entry to be added.

The BlockingCollection<T> class works very well for this type of scenario. You can have multiple threads each add a new "entry" to the collection, and a single thread running in the background that just calls GetConsumingEnumerable(), and writes out all of the values.


You are trying to write to a file from multiple threads - this is not possible without some sort of synchronization to ensure the file is closed before attempting to write by another thread.

As for FileShare set to None - this means that multiple threads are not allowed to share the file, so of course you get a sharing violation exception.

None - Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.

0

精彩评论

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