我不想在进程之间阻塞一些代码,这主要是为我的UWP应用程序编写的,但是由于它是一个跨平台项目,这段代码也是在Android应用程序上执行的:
if (!Semaphore.TryOpenExisting("some_name", out _semaphore))
_semaphore = new Semaphore(1, 1, "some_name");其中_semaphore是:
private readonly Semaphore _semaphore;因此,现在当调用Semaphore.TryOpenExisting时,我得到以下异常:System.NotSupportedException: Specified method is not supported.。
但是从Xamarin博士的角度来看,Semaphore.TryOpenExisting看起来很简单,而且我没有看到任何在某些平台上不支持的信息?
我做错什么了?为了跨平台,我应该放弃Semaphore类吗?如何在跨平台场景中实现?
发布于 2016-12-04 01:37:59
因此,对于Android,我不需要经典的System.Threading.Semaphore类提供的进程间同步,这类在Xamarin.Android中看起来不受支持,但我仍然希望在进程中具有命名信号量的功能,以便与我的UWP应用程序具有一致的行为,我编写了下面的帮助类,以便使用SemaphoreSlim类在“命名”锁中运行代码:
class NamedSlimLocker
{
private static readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreSlimDict;
static NamedSlimLocker()
{
_semaphoreSlimDict = new ConcurrentDictionary<string, SemaphoreSlim>();
}
private readonly string _name;
private readonly SemaphoreSlim _semaphore;
public NamedSlimLocker(string name)
{
this._name = name;
_semaphore = _semaphoreSlimDict.GetOrAdd(name, (n) => new SemaphoreSlim(1,1));
}
public async Task RunLockedAsync(Func<Task> action)
{
try
{
await _semaphore.WaitAsync();
await action();
}
finally
{
_semaphore.Release();
}
}
public async Task<T> RunLockedAsync<T>(Func<Task<T>> action)
{
try
{
await _semaphore.WaitAsync();
return await action();
}
finally
{
_semaphore.Release();
}
}
}https://stackoverflow.com/questions/40948595
复制相似问题