简体   繁体   English

Mutex和Windows Phone 8.1

[英]Mutex and Windows Phone 8.1

Here's my problem. 这是我的问题。 Windows Phone 8.1 Visual Studio 2013 Release 4 Windows Phone 8.1 Visual Studio 2013第4版

I've got a main project, and a background project that runs every 30 minutes. 我有一个主要项目,以及每30分钟运行一次的后台项目。 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. 我想确保在Windows.Storage.ApplicationData.Current.LocalSettings中独占访问存储,所以我使用的是Mutex。

In my main XAML project, I create and use a Mutex named "B+DBgMu" (don't ask). 在我的主要XAML项目中,我创建并使用名为“B + DBgMu”的互斥锁(不要问)。

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. 我可靠地获得Mutex并访问共享存储。

In my background project, I attempt to (I think) acquire the same Mutex, only the Mutex is never acquired: 在我的后台项目中,我尝试(我认为)获得相同的Mutex,只有Mutex从未获得:

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. 我已经浏览过Web,特别是StackOverflow,但我想知道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. 在这里使用true就是你的bug。 That gives your main thread immediate ownership of the Mutex. 这使您的主线程立即拥有Mutex。 Mutex is re-entrant, calling WaitOne() next simply increments the usage count. Mutex是可重入的,稍后调用WaitOne()会增加使用次数。 And calling ReleaseMutex() simply decrements it. 并且调用ReleaseMutex()只是递减它。 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. 简单修复,传递错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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