Skip to content

Instantly share code, notes, and snippets.

@erikporter
Last active January 2, 2016 18:39
Show Gist options
  • Save erikporter/8345108 to your computer and use it in GitHub Desktop.
Save erikporter/8345108 to your computer and use it in GitHub Desktop.
Example of using a Mutex to lock some async file system calls in WP8.
public class FileStorage : IDisposable {
private static readonly Dictionary<string, Mutex> Mutexes = new Dictionary<string, Mutex>();
public async Task DoSomethingAsync(string accountId) {
var mutex = GetMutex(accountId);
try {
mutex.WaitOne();
// Do something to files
}
finally {
mutex.ReleaseMutex();
}
}
private static Mutex GetMutex(string accountId) {
if (Mutexes.ContainsKey(accountId)) {
return Mutexes[accountId];
}
var mutex = new Mutex(false, accountId);
Mutexes.Add(accountId, mutex);
return mutex;
}
public void Dispose() {
foreach (var mutex in Mutexes) {
mutex.Value.Dispose();
}
Mutexes.Clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment