-
Notifications
You must be signed in to change notification settings - Fork 22
/
DiceAsyncResult.cs
65 lines (61 loc) · 1.96 KB
/
DiceAsyncResult.cs
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Threading;
namespace Dice.Client.Web
{
/// <summary>
/// Supports the .NET 3.5 Begin/End async pattern.
/// </summary>
internal sealed class DiceAsyncResult<T> : IAsyncResult, IDisposable where T : DiceResponse
{
public T Response;
public object AsyncState { get; set; }
ManualResetEvent _AsyncWaitHandle;
public WaitHandle AsyncWaitHandle
{
get
{
if (_AsyncWaitHandle != null)
return _AsyncWaitHandle;
ManualResetEvent w = new ManualResetEvent(false);
if (Interlocked.CompareExchange(ref _AsyncWaitHandle, w, null) != null)
w.Close();
else if (IsCompleted)
w.Set();
return _AsyncWaitHandle;
}
}
public bool CompletedSynchronously { get; set; }
int Completed;
public bool IsCompleted { get { return Interlocked.CompareExchange(ref Completed, 1, 1) != 0; } }
public AsyncCallback Callback;
public Exception Exception;
public void Complete(Exception e)
{
Exception = e;
Complete((T)null);
}
public void Complete(T response)
{
if (response != null)
Response = response;
Interlocked.Exchange(ref Completed, 1);
ManualResetEvent w = _AsyncWaitHandle;
if (w != null)
w.Set();
AsyncCallback c = Callback;
if (c != null)
c(this);
}
public DiceAsyncResult(AsyncCallback callback, object state)
{
Callback = callback;
AsyncState = state;
}
public void Dispose()
{
WaitHandle w = _AsyncWaitHandle;
if (w != null)
w.Close();
}
}
}