我正在使用并发字典来保存打开的文件。
要打开一个新文件,我这样做:
myDictionary.GetOrAdd (fName, (fn) => new StreamWriter(fn, true));
有了这个,我经常得到以下异常:
System.IO.IOException: The process cannot access the file '....' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPa
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append)
对我来说,这意味着该操作不是原子的,并且该软件试图两次打开同一个文件。
有没有其他我可以使用的操作,这将是原子的?出于性能考虑,我想避免锁定。