| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
using System.Collections.Generic; |
| 4 |
|
| 5 |
namespace System.Reactive.Concurrency |
| 6 |
{ |
| 7 |
/// <summary> |
| 8 |
/// Asynchronous lock. |
| 9 |
/// </summary> |
| 10 |
public sealed class AsyncLock : IDisposable |
| 11 |
{ |
| 12 |
private readonly Queue<Action> queue = new Queue<Action>(); |
| 13 |
private bool isAcquired = false; |
| 14 |
private bool hasFaulted = false; |
| 15 |
|
| 16 |
/// <summary> |
| 17 |
/// Queues the action for execution. If the caller acquires the lock and becomes the owner, |
| 18 |
/// the queue is processed. If the lock is already owned, the action is queued and will get |
| 19 |
/// processed by the owner. |
| 20 |
/// </summary> |
| 21 |
/// <param name="action">Action to queue for execution.</param> |
| 22 |
/// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception> |
| 23 |
public void Wait(Action action) |
| 24 |
{ |
| 25 |
if (action == null) |
| 26 |
throw new ArgumentNullException("action"); |
| 27 |
|
| 28 |
var isOwner = false; |
| 29 |
lock (queue) |
| 30 |
{ |
| 31 |
if (!hasFaulted) |
| 32 |
{ |
| 33 |
queue.Enqueue(action); |
| 34 |
isOwner = !isAcquired; |
| 35 |
isAcquired = true; |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
if (isOwner) |
| 40 |
{ |
| 41 |
while (true) |
| 42 |
{ |
| 43 |
var work = default(Action); |
| 44 |
lock (queue) |
| 45 |
{ |
| 46 |
if (queue.Count > 0) |
| 47 |
work = queue.Dequeue(); |
| 48 |
else |
| 49 |
{ |
| 50 |
isAcquired = false; |
| 51 |
break; |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
try |
| 56 |
{ |
| 57 |
work(); |
| 58 |
} |
| 59 |
catch |
| 60 |
{ |
| 61 |
lock (queue) |
| 62 |
{ |
| 63 |
queue.Clear(); |
| 64 |
hasFaulted = true; |
| 65 |
} |
| 66 |
throw; |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
/// <summary> |
| 73 |
/// Clears the work items in the queue and drops further work being queued. |
| 74 |
/// </summary> |
| 75 |
public void Dispose() |
| 76 |
{ |
| 77 |
lock (queue) |
| 78 |
{ |
| 79 |
queue.Clear(); |
| 80 |
hasFaulted = true; |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
} |