5

How can I write to a file using await FileIO.WriteTextAsync() (in Windows Phone 8.1) after acquiring mutex so that no two threads access the same file and mutual exclusion is ensured. I'm doing the following:

mutex.WaitOne() try { await FileIO.WriteTextAsync(filename, text); Debug.WriteLine("written"); } finally { mutex.ReleaseMutex(); } 

But the method works for one or two iterations only, after which it throws a System.Exception. Also, if I remove the await keyword or remove the file writing method entirely, the code runs perfectly fine. So, all trouble is caused by calling an async method. What can I do to resolve this?

1
  • 1
    If you are guarding resources in the same process then Luaan's answer should do the job. In case you need to guard resources between processes (the main role of mutex as I think) then take a look at this question. Commented Jul 30, 2015 at 8:02

1 Answer 1

11

This is a job for a monitor (or to make this more async-friendly, a semaphore), not a mutex.

The problem is that the continuation to WriteTextAsync is likely to run on a separate thread, so it can't release the mutex - that can only be done from the same thread that originally acquired the mutex.

var semaphore = new SemaphoreSlim(1); await semaphore.WaitAsync(); try { await FileIO.WriteTextAsync(filename, text); Debug.WriteLine("written"); } finally { semaphore.Release(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.