Mutex and Windows Phone 8.1

随声附和 提交于 2019-12-22 09:42:08

问题


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?


回答1:


   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.



来源:https://stackoverflow.com/questions/33534243/mutex-and-windows-phone-8-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!