简体   繁体   English

Mutex和Windows Phone 8.1 Silverlight

[英]Mutex and Windows Phone 8.1 Silverlight

I want to prevent my Background Process from performing an action if the app is open in the foreground. 如果应用程序在前台打开,我想阻止后台进程执行操作。 I found a similar question posed here , but I can't get it to work for me. 我在这里发现了一个类似的问题,但是我无法解决这个问题。 When my Background Process checks the Mutex, it is never already in existence. 当我的后台进程检查互斥对象时,它从来就不存在。 When the foreground app starts I create a Mutex like so: 当前台应用启动时,我将创建一个互斥体,如下所示:

public void Application_Launching(object sender, LaunchingEventArgs e)
{
    var myMutex = new Mutex(false, "MUTEX_NAME");
}

I release it when the foreground app closes: 我在前景应用关闭时释放它:

private void Application_Closing(object sender, ClosingEventArgs e)
{
    var myMutex = new Mutex(false, "MUTEX_NAME");
    myMutex.ReleaseMutex();
}

In the Background Process I have the following check: 在后台进程中,我进行了以下检查:

bool IsMutexLocked()
{
    var myMutex = new Mutex(false, "MUTEX_NAME"); 
    return myMutex.WaitOne(100); 
}

I'm assuming here that WaitOne returns true if "MUTEX_NAME" doesn't exist, or it does exist but gets released after 100ms. 我在这里假设,如果"MUTEX_NAME"不存在,或者它确实存在但在100毫秒后被释放,则WaitOne将返回true。 I've also tried using the out createdNew in the Mutex constructor, and the static methods OpenExisting and TryOpenExisting but to no avail. 我还尝试过在Mutex构造函数中使用out createdNew以及静态方法OpenExistingTryOpenExisting但无济于事。

You are not locking your mutex in main app, you just create it (also without ownership). 您并不是将互斥锁锁定在主应用程序中,而只是创建它(也没有所有权)。 You can either create Mutex with initial ownership or call WaitOne() when needed. 您可以创建具有初始所有权的Mutex,也可以在需要时调用WaitOne() Some more help at Joe Alabhari's blog . Joe Alabhari的博客中提供了更多帮助。

public void Application_Launching(object sender, LaunchingEventArgs e)
{
    var myMutex = new Mutex(true, "MUTEX_NAME");
    // or call myMutex.WaitOne() // here maybe some timeout handling
}

Also I don't think that holding a mutex until the app is closed is a good practise - lock the mutex only when you really need to (for example access to common file). 我也不认为在关闭应用程序之前保持互斥不是一个好习惯-仅在确实需要时才锁定互斥(例如访问公用文件)。 If you really want to try this, create a global mutex instance upon launching, then release it upon closing, but without obtaining it again, just use previous instance. 如果您真的想尝试此操作,请在启动时创建一个全局互斥体实例,然后在关闭时释放它,但是无需再次获取它,只需使用先前的实例即可。

Look out for couple of things - don't leave abandoned mutexes, look out so it's not garbage collected, release it when needed. 注意几件事-不要留下废弃的互斥锁,注意不要被垃圾回收,需要时将其释放。 There are plenty of posts about this synchronization object, here you have a good pattern . 关于此同步对象的文章很多, 这里有一个不错的模式

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

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