forked from sh-akira/VirtualMotionCapture
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncLock.cs
More file actions
40 lines (37 loc) · 1.19 KB
/
AsyncLock.cs
File metadata and controls
40 lines (37 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnityMemoryMappedFile
{
public sealed class AsyncLock
{
private readonly System.Threading.SemaphoreSlim m_semaphore
= new System.Threading.SemaphoreSlim(1, 1);
private readonly Task<IDisposable> m_releaser;
public AsyncLock()
{
m_releaser = Task.FromResult((IDisposable)new Releaser(this));
}
public Task<IDisposable> LockAsync()
{
var wait = m_semaphore.WaitAsync();
return wait.IsCompleted ?
m_releaser :
wait.ContinueWith(
(_, state) => (IDisposable)state,
m_releaser.Result,
System.Threading.CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default
);
}
private sealed class Releaser : IDisposable
{
private readonly AsyncLock m_toRelease;
internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; }
public void Dispose() { m_toRelease.m_semaphore.Release(); }
}
}
}