@@ -66,8 +66,8 @@ public SharedFileSink(string path, ITextFormatter textFormatter, long? fileSizeL
6666 Directory . CreateDirectory ( directory ) ;
6767 }
6868
69- // Backslash is special on Windows
70- _mutex = new Mutex ( false , path . Replace ( ' \\ ' , ':' ) + MutexNameSuffix ) ;
69+ var mutexName = Path . GetFullPath ( path ) . Replace ( Path . DirectorySeparatorChar , ':' ) + MutexNameSuffix ;
70+ _mutex = new Mutex ( false , mutexName ) ;
7171 _underlyingStream = System . IO . File . Open ( path , FileMode . Append , FileAccess . Write , FileShare . ReadWrite ) ;
7272 _output = new StreamWriter ( _underlyingStream , encoding ?? new UTF8Encoding ( encoderShouldEmitUTF8Identifier : false ) ) ;
7373 }
@@ -82,11 +82,8 @@ public void Emit(LogEvent logEvent)
8282
8383 lock ( _syncRoot )
8484 {
85- if ( ! _mutex . WaitOne ( MutexWaitTimeout ) )
86- {
87- SelfLog . WriteLine ( "Shared file mutex could not be acquired in {0} ms for event emitting" , MutexWaitTimeout ) ;
85+ if ( ! TryAcquireMutex ( ) )
8886 return ;
89- }
9087
9188 try
9289 {
@@ -103,7 +100,7 @@ public void Emit(LogEvent logEvent)
103100 }
104101 finally
105102 {
106- _mutex . ReleaseMutex ( ) ;
103+ ReleaseMutex ( ) ;
107104 }
108105 }
109106 }
@@ -123,21 +120,41 @@ public void FlushToDisk()
123120 {
124121 lock ( _syncRoot )
125122 {
126- if ( ! _mutex . WaitOne ( MutexWaitTimeout ) )
127- {
128- SelfLog . WriteLine ( "Shared file mutex could not be acquired in {0} ms for disk flush operation" , MutexWaitTimeout ) ;
123+ if ( ! TryAcquireMutex ( ) )
129124 return ;
130- }
131125
132126 try
133127 {
134128 _underlyingStream . Flush ( true ) ;
135129 }
136130 finally
137131 {
138- _mutex . ReleaseMutex ( ) ;
132+ ReleaseMutex ( ) ;
133+ }
134+ }
135+ }
136+
137+ bool TryAcquireMutex ( )
138+ {
139+ try
140+ {
141+ if ( ! _mutex . WaitOne ( MutexWaitTimeout ) )
142+ {
143+ SelfLog . WriteLine ( "Shared file mutex could not be acquired within {0} ms" , MutexWaitTimeout ) ;
144+ return false ;
139145 }
140146 }
147+ catch ( AbandonedMutexException )
148+ {
149+ SelfLog . WriteLine ( "Inherited shared file mutex after abandonment by another process" ) ;
150+ }
151+
152+ return true ;
153+ }
154+
155+ void ReleaseMutex ( )
156+ {
157+ _mutex . ReleaseMutex ( ) ;
141158 }
142159 }
143160}
0 commit comments