简体   繁体   中英

Mutex and Windows Phone 8.1

Here's my problem. Windows Phone 8.1 Visual Studio 2013 Release 4

I've got a main project, and a background project that runs every 30 minutes. I want to pass data between the two. I want to ensure exclusive access to storage in Windows.Storage.ApplicationData.Current.LocalSettings, so I'm using a Mutex.

In my main XAML project, I create and use a Mutex named "B+DBgMu" (don't ask).

public static Mutex Mu = null;      // A Mutex
Mu = new Mutex (true, "B+DBgMu");   // Create a Mutex. This is done only once.

if (App.Mu.WaitOne (200))           // Wait for exclusive access. This is done often.
{
    < PROTECTED CODE GOES HERE>

    App.Mu.ReleaseMutex ();     // Release our lock on application storage.
}

I reliably get the Mutex and access to the shared storage.

In my background project, I attempt to (I think) acquire the same Mutex, only the Mutex is never acquired:

Mutex Mu = new Mutex (false, "B+DBgMu");    // Hook onto the Mutex.
if (Mu.WaitOne (1000))              // Wait (quite a while) for it.
{
    < PROTECTED CODE GOES HERE
    and it NEVER EXECUTES>

    App.Mu.ReleaseMutex ();         // Release our lock.
}

I've scoured the Web, especially StackOverflow, but I wonder how much of what's there applies to the Windows Phone. What am I doing wrong?

   Mu = new Mutex (true, "B+DBgMu");   // Create a Mutex. This is done only once.

Using true here is your bug. That gives your main thread immediate ownership of the Mutex. Mutex is re-entrant, calling WaitOne() next simply increments the usage count. And calling ReleaseMutex() simply decrements it. It never goes to zero.

So your main thread always owns the mutex and your background worker can never acquire it. Simple fix, pass false instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM