Repository navigation
Expand file tree
/
Copy pathUpdateProcessAsyncResult.cs
More file actions
106 lines (92 loc) · 2.7 KB
/
Copy pathUpdateProcessAsyncResult.cs
File metadata and controls
106 lines (92 loc) · 2.7 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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Threading;
namespace NAppUpdate.Framework.Common
{
public class UpdateProcessAsyncResult : IAsyncResult
{
private readonly AsyncCallback _asyncCallback;
private readonly Object _asyncState;
private const Int32 StatePending = 0;
private const Int32 StateCompletedSynchronously = 1;
private const Int32 StateCompletedAsynchronously = 2;
private Int32 _completedState = StatePending;
private ManualResetEvent _asyncWaitHandle;
private Exception _exception;
public UpdateProcessAsyncResult(AsyncCallback asyncCallback, Object state)
{
_asyncCallback = asyncCallback;
_asyncState = state;
}
public void SetAsCompleted(Exception exception, Boolean completedSynchronously)
{
// Passing null for exception means no error occurred.
// This is the common case
_exception = exception;
// The m_CompletedState field MUST be set prior calling the callback
Int32 prevState = Interlocked.Exchange(ref _completedState,
completedSynchronously ? StateCompletedSynchronously : StateCompletedAsynchronously);
if (prevState != StatePending)
throw new InvalidOperationException("You can set a result only once");
// If the event exists, set it
if (_asyncWaitHandle != null) _asyncWaitHandle.Set();
// If a callback method was set, call it
if (_asyncCallback != null) _asyncCallback(this);
}
public void EndInvoke()
{
// This method assumes that only 1 thread calls EndInvoke
// for this object
if (!IsCompleted)
{
// If the operation isn't done, wait for it
AsyncWaitHandle.WaitOne();
AsyncWaitHandle.Close();
_asyncWaitHandle = null; // Allow early GC
}
// Operation is done: if an exception occured, throw it
if (_exception != null) throw _exception;
}
public bool IsCompleted
{
get
{
return Thread.VolatileRead(ref _completedState) != StatePending;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (_asyncWaitHandle == null)
{
bool done = IsCompleted;
var mre = new ManualResetEvent(done);
if (Interlocked.CompareExchange(ref _asyncWaitHandle, mre, null) != null)
{
// Another thread created this object's event; dispose
// the event we just created
mre.Close();
}
else
{
if (!done && IsCompleted)
{
// If the operation wasn't done when we created
// the event but now it is done, set the event
_asyncWaitHandle.Set();
}
}
}
return _asyncWaitHandle;
}
}
public Object AsyncState { get { return _asyncState; } }
public Boolean CompletedSynchronously
{
get
{
return Thread.VolatileRead(ref _completedState) == StateCompletedSynchronously;
}
}
}
}