main
 1using System;
 2using System.Threading;
 3
 4namespace momoney.service.infrastructure.threading
 5{
 6    [Serializable]
 7    internal class WorkItem : IAsyncResult
 8    {
 9        readonly object[] args;
10        readonly object async_state;
11        bool completed;
12        readonly Delegate method;
13        readonly ManualResetEvent reset_event;
14        object returned_value;
15
16        internal WorkItem(object async_state, Delegate method, object[] args)
17        {
18            this.async_state = async_state;
19            this.method = method;
20            this.args = args;
21            reset_event = new ManualResetEvent(false);
22            completed = false;
23        }
24
25        //IAsyncResult properties 
26        object IAsyncResult.AsyncState
27        {
28            get { return async_state; }
29        }
30
31        WaitHandle IAsyncResult.AsyncWaitHandle
32        {
33            get { return reset_event; }
34        }
35
36        bool IAsyncResult.CompletedSynchronously
37        {
38            get { return false; }
39        }
40
41        bool IAsyncResult.IsCompleted
42        {
43            get { return Completed; }
44        }
45
46        bool Completed
47        {
48            get
49            {
50                lock (this)
51                {
52                    return completed;
53                }
54            }
55            set
56            {
57                lock (this)
58                {
59                    completed = value;
60                }
61            }
62        }
63
64        //This method is called on the worker thread to execute the method
65        internal void CallBack()
66        {
67            MethodReturnedValue = method.DynamicInvoke(args);
68            //Method is done. Signal the world
69            reset_event.Set();
70            Completed = true;
71        }
72
73        internal object MethodReturnedValue
74        {
75            get
76            {
77                object method_returned_value;
78                lock (this)
79                {
80                    method_returned_value = returned_value;
81                }
82                return method_returned_value;
83            }
84            set
85            {
86                lock (this)
87                {
88                    returned_value = value;
89                }
90            }
91        }
92    }
93}