Xamarin Android: Semaphore.TryOpenExisting 不工作

Xamarin Android: Semaphore.TryOpenExisting not working

我不想在进程之间阻塞一些代码,它主要针对我的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 Docs 看起来 Semaphore.TryOpenExisting 是简单化的,我没有看到某些平台不支持的信息?

我做错了什么?我应该放弃跨平台的 Semaphore class 吗?跨平台场景如何实现?

所以,因为 Android 我不需要 classic System.Threading.Semaphore class 提供的进程间同步,这看起来不受支持Xamarin.Android,但我仍然希望在进程中具有命名信号量的功能,以便与我的 UWP 应用程序具有一致的行为,我在 [=15] 中为 运行 代码编写了以下帮助程序 class =] 锁定使用 SemaphoreSlim class:

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();
        }
    }
}