12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
-
- using System;
- using System.Collections.Generic;
- namespace UniRx.InternalUtil
- {
-
-
-
- internal sealed class AsyncLock : IDisposable
- {
- private readonly Queue<Action> queue = new Queue<Action>();
- private bool isAcquired = false;
- private bool hasFaulted = false;
-
-
-
-
-
-
-
- public void Wait(Action action)
- {
- if (action == null)
- throw new ArgumentNullException("action");
- var isOwner = false;
- lock (queue)
- {
- if (!hasFaulted)
- {
- queue.Enqueue(action);
- isOwner = !isAcquired;
- isAcquired = true;
- }
- }
- if (isOwner)
- {
- while (true)
- {
- var work = default(Action);
- lock (queue)
- {
- if (queue.Count > 0)
- work = queue.Dequeue();
- else
- {
- isAcquired = false;
- break;
- }
- }
- try
- {
- work();
- }
- catch
- {
- lock (queue)
- {
- queue.Clear();
- hasFaulted = true;
- }
- throw;
- }
- }
- }
- }
-
-
-
- public void Dispose()
- {
- lock (queue)
- {
- queue.Clear();
- hasFaulted = true;
- }
- }
- }
- }
|