private static void CleanUpMessages(object state) { var directory = (DirectoryInfo) state; bool createdNew; var mutexName = string.Concat(MutexCleanUpKey, ".", directory.Name); var accessControl = new MutexSecurity(); var sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); accessControl.SetAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow)); using (var mutex = new Mutex(true, mutexName, out createdNew, accessControl)) { if (createdNew) { try { Thread.Sleep(FileTimeoutMilliseconds); } catch (ThreadInterruptedException) { } CleanUpMessages(directory); mutex.ReleaseMutex(); } } if (createdNew) { ThreadPool.QueueUserWorkItem(CleanUpMessages, directory); } }
/// <summary> /// This method is called within a seperate thread and deletes messages that are older than /// the pre-defined expiry time. /// </summary> /// <param name = "state"></param> private static void CleanUpMessages(object state) { var directory = (DirectoryInfo) state; // use a mutex to ensure only one listener system wide is running bool createdNew; string mutexName = string.Concat(mutexCleanUpKey, ".", directory.Name); var accessControl = new MutexSecurity(); var sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); accessControl.SetAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow)); using (var mutex = new Mutex(true, mutexName, out createdNew, accessControl)) { // we this thread owns the Mutex then clean up otherwise exit. if (createdNew) { // wait for the specified timeout before attempting to clean directory try { Thread.Sleep(fileTimeoutMilliseconds); } catch (ThreadInterruptedException) { } CleanUpMessages(directory); // release the mutex mutex.ReleaseMutex(); } } if (createdNew) { // after mutex release add an additional thread for cleanup in case we're the last out // and there are now additional files to clean ThreadPool.QueueUserWorkItem(CleanUpMessages, directory); } }