Michael Sabin
Michael Sabin

Reputation: 1759

Windows Phone Periodic Task Synchronization Async Methods

I am attempting to make use of a Periodic Background Task on a Windows Phone 8 app. I want to use a xml file to serialize state information between the foreground app and the background task.

I read that you should use a Mutex to synchronize access to the file. However, I run into issues using it, because I need to call await in the method that I use the Mutex in (to read and write data to a file). This causes my app to lock up when I call Mutex.Release, since it is being released on a different thread. Any ideas how to handle this?

    public async Task WriteState(BackgroundTaskState state)
    {            
        using (var m = new Mutex(false, BackgroundTaskState.MutexName))
        {

            try
            {
                m.WaitOne();

                using (var stream = await GetFileStreamForWriting())
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTaskState));
                    xmlSerializer.Serialize(stream, state);
                    await stream.FlushAsync();
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                m.ReleaseMutex();
            }
        }
    }

Upvotes: 1

Views: 258

Answers (1)

Rafa Paez
Rafa Paez

Reputation: 4860

A Mutex must only be released by the same thread that acquired it so you cannot using it with await. You can use Semaphore to achieve the same result, since they are not bounded to ant particular thread.

semaphore.WaitOne();
await Task.Delay(2); // Your async call
semaphore.Release();

Upvotes: 1

Related Questions