互斥和Windows Phone 8.1 [英] Mutex and Windows Phone 8.1

查看:135
本文介绍了互斥和Windows Phone 8.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的问题。
的Windows Phone 8.1的Visual Studio 2013发布4



我有一个主要项目,即每30分钟一班背景的项目。我想在二者之间传递数据。我要确保存储在Windows.Storage.ApplicationData.Current.LocalSettings独占访问,所以我使用一个互斥。



在我的主要XAML的项目,我创建,并使用名为b + DBgMu(不要问)互斥

 公共静态互斥亩= NULL; //互斥
亩=新的Mutex(真,B + DBgMu); //创建一个互斥。这只需进行一次。

如果(App.Mu.WaitOne(200))//等待独占访问。这通常完成。
{
<受保护的代码GOES HERE>

App.Mu.ReleaseMutex(); //释放我们的应用程序存储锁。
}



我确实得到互斥锁,并访问共享存储。



在我的背景的项目,我尝试(我认为)获得相同的互斥体,只有互斥从未获得​​:

 互斥亩=新的Mutex(假,B + DBgMu); //钩住互斥。 
如果(Mu.WaitOne(1000))//等待(相当长的一段)它。
{
<受保护的代码GOES HERE
,它永远不会执行>

App.Mu.ReleaseMutex(); //释放我们的锁。
}



我已经冲刷网页,尤其是计算器,但我不知道有多少那里的东西应用到了Windows Phone。
我在做什么错了?


解决方案

 亩=新的Mutex(真,B + DBgMu); //创建一个互斥。这只需进行一次。 



使用的真正的这里是你的错误。这给了互斥的你的主线程立即所有权。互斥锁重入,调用了WaitOne()旁边只是增加使用计数。并调用ReleaseMutex(),只需将它减。它永远不会变为零。



所以,你的主线程的总是的拥有互斥和你的背景工人不能获得它。简单的修复,通过的的代替。


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.

这篇关于互斥和Windows Phone 8.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆