EventService.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6. using Aitex.Core.RT.Log;
  7. using Aitex.Core.RT.Event;
  8. using Aitex.Core.Util;
  9. using Aitex.Core.WCF.Interface;
  10. using System.Collections.Concurrent;
  11. namespace Aitex.Core.WCF
  12. {
  13. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
  14. public class EventService : IEventService
  15. {
  16. ConcurrentDictionary<Guid, IEventServiceCallback> _callbackClientList = new ConcurrentDictionary<Guid, IEventServiceCallback>();
  17. public event Action<EventItem> OnEvent;
  18. private int _counter;
  19. public EventService()
  20. {
  21. }
  22. public void FireEvent(EventItem obj)
  23. {
  24. //DeviceTimer _timer = new DeviceTimer();
  25. //_timer.Start(0);
  26. //double t1 = 0;
  27. //double t2 = 0;
  28. //double t3 = 0;
  29. //t1 = _timer.GetElapseTime();
  30. Guid[] ids = _callbackClientList.Keys.ToArray();
  31. for (int i = 0; i < ids.Length; i++)
  32. {
  33. try
  34. {
  35. //t2 = _timer.GetElapseTime() - t1;
  36. _callbackClientList[ids[i]].SendEvent(obj);
  37. //t3 = _timer.GetElapseTime() - t2;
  38. }
  39. catch (Exception ex)
  40. {
  41. LOG.Error(string.Format("给客户端{0}发送事件失败,客户端被删除.", ids[i]), ex);
  42. IEventServiceCallback service;
  43. _callbackClientList.TryRemove(ids[i], out service);
  44. }
  45. }
  46. if (OnEvent != null)
  47. {
  48. OnEvent(obj);
  49. }
  50. //System.Diagnostics.Trace.WriteLine(string.Format("[{0}] ----- [{1}] --------- [{2}]", t1, t2, t3));
  51. }
  52. public bool Register(Guid id)
  53. {
  54. try
  55. {
  56. if (!_callbackClientList.ContainsKey(id))
  57. {
  58. LOG.Info(string.Format("客户端{0}已连接", id.ToString()), true);
  59. }
  60. _callbackClientList[id] = OperationContext.Current.GetCallbackChannel<IEventServiceCallback>();
  61. }
  62. catch (Exception ex)
  63. {
  64. LOG.Error("监听事件发生错误", ex);
  65. }
  66. return true;
  67. }
  68. public void UnRegister(Guid id)
  69. {
  70. if (!_callbackClientList.ContainsKey(id))
  71. {
  72. LOG.Info(string.Format("客户端{0}断开连接", id.ToString()), true);
  73. }
  74. IEventServiceCallback service;
  75. _callbackClientList.TryRemove(id, out service);
  76. }
  77. public int Heartbeat()
  78. {
  79. return _counter++ % 100000;
  80. }
  81. }
  82. }