1: public class AsyncQueueManager
2: {
3: private ILog _logger = log4net.LogManager.GetLogger(typeof(AsyncQueueManager));
4: private ManualResetEvent _WaitHandle = new ManualResetEvent(true);
5: private int _QueueCount = 0;
6: object locker = new object();
7:
8: private Action<object> GetActionWrapper(Action<object> action)
9: {
10: Action<object> actionWrapper = (object obj) =>
11: {
12: try
13: {
14: action(obj);
15: }
16: catch(Exception ex)
17: {
18: LogException(action, ex);
19: }
20: finally
21: {
22: lock (locker)
23: _QueueCount = _QueueCount - 1;
24: SetWaitHandle();
25: }
26: };
27: return actionWrapper;
28: }
29: public AsyncQueueManager Queue(Action<object> action)
30: {
31: lock(locker)
32: _QueueCount = _QueueCount + 1;
33: _WaitHandle.Reset();
34: Action<object> actionWrapper = GetActionWrapper(action);
35: WaitCallback waitCallback = new WaitCallback(actionWrapper);
36: ThreadPool.QueueUserWorkItem(waitCallback);
37: return this;
38: }
39: private void SetWaitHandle()
40: {
41: if (_QueueCount == 0)
42: {
43: _WaitHandle.Set();
44: }
45: }
46:
47: public void WaitOne()
48: {
49: _WaitHandle.WaitOne();
50: }
51:
52: public void WaitOne(TimeSpan timeout)
53: {
54: _WaitHandle.WaitOne(timeout);
55: }
56:
57: private void LogException(Action<object> action, Exception ex)
58: {
59: string exceptionString = "Exception occured while running async operation." +
60: " Details below." + Environment.NewLine +
61: "Method name:" + action.Method.Name + Environment.NewLine +
62: "Exception:" + ex.ToString();
63: _logger.Error(exceptionString);
64: }
65: }