WP8 Mutex - 资源锁定 [英] WP8 Mutex - Resource Locking
问题描述
我在理解 Mutex 类以及如何在 WP8 应用程序中正确使用它时遇到问题.我试图做的是一次只允许 ScheduledAgent 或应用程序将文件读/写到存储.我已经尝试了各种方法,但都没有运气.任何帮助将不胜感激.
I'm having issues understanding the Mutex class and how to properly use it in a WP8 application. What I'm attempting to do is allow only a ScheduledAgent or the application to read/write a file to storage at a time. I've tried this various ways with no luck. Any help would be appreciated.
调度代理代码:
当我调用 ReleaseMutex() 时,下面的代码出错了.当我像这样创建 Mutex 对象时,这个问题得到了解决:new Mutex(true, "FlightPathData").但是我永远无法获得锁并挂在 WaitOne()
Below code errors out when I call ReleaseMutex(). This issue is fixed when I create the Mutex object like so: new Mutex(true, "FlightPathData"). But then I can never get a lock and hangs on WaitOne()
错误
从未同步的代码块调用对象同步方法.
Object synchronization method was called from an unsynchronized block of code.
代码
readonly Mutex mutex = new Mutex(false, "FlightPathData");
protected async override void OnInvoke(ScheduledTask task)
{
List<METAR> savedMetars = null;
var facility = ....;
bool mutexAcquired = mutex.WaitOne();
try
{
if (mutexAcquired)
{
savedMetars = await Data.LoadMetarsAsync(facility.Identifier);
//Thread.Sleep(15000);
}
}
finally
{
if (mutexAcquired)
{
mutex.ReleaseMutex();
}
}
NotifyComplete();
}
ViewModelCode(工作正常,直到 ScheduledAgent ReleaseMutex() 失败)
ViewModelCode (Works fine till the ScheduledAgent ReleaseMutex() fails)
static readonly Mutex mutex = new Mutex(true, "FlightPathData");
...
mutex.WaitOne();
var savedMetars = await Data.LoadMetarsAsync(this.Facility.Identifier);
mutex.ReleaseMutex();
推荐答案
您不能将线程仿射锁与 async
代码一起使用.这是因为 await
可以导致方法返回(同时持有互斥锁),然后另一个线程可以继续 async
方法并尝试释放它不拥有的互斥锁.如果这令人困惑,我有一个 async
介绍可能对您有帮助的博文.
You can't use thread-affine locks with async
code. This is because the await
can cause the method to return (while holding the mutex) and then another thread can continue the async
method and attempt to release a mutex it does not own. If this is confusing, I have an async
intro blog post that you may find helpful.
所以你不能使用Mutex
或其他线程仿射锁,比如lock
.但是,您可以使用 SemaphoreSlim
.在您的 async
方法中,您将使用 await WaitAsync
而不是 Wait
.
So you can't use Mutex
or other thread-affine locks such as lock
. However, you can use SemaphoreSlim
. In your async
methods, you would use await WaitAsync
instead of Wait
.
这篇关于WP8 Mutex - 资源锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!