EventService.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 EventService()
  18. {
  19. }
  20. public void FireEvent(EventItem obj)
  21. {
  22. //DeviceTimer _timer = new DeviceTimer();
  23. //_timer.Start(0);
  24. //double t1 = 0;
  25. //double t2 = 0;
  26. //double t3 = 0;
  27. //t1 = _timer.GetElapseTime();
  28. Guid[] ids = _callbackClientList.Keys.ToArray();
  29. for (int i = 0; i < ids.Length; i++)
  30. {
  31. try
  32. {
  33. //t2 = _timer.GetElapseTime() - t1;
  34. _callbackClientList[ids[i]].SendEvent(obj);
  35. //t3 = _timer.GetElapseTime() - t2;
  36. }
  37. catch (Exception ex)
  38. {
  39. LOG.Error(string.Format("给客户端{0}发送事件失败,客户端被删除。", ids[i]), ex);
  40. IEventServiceCallback service;
  41. _callbackClientList.TryRemove(ids[i], out service);
  42. }
  43. }
  44. //System.Diagnostics.Trace.WriteLine(string.Format("[{0}] ----- [{1}] --------- [{2}]", t1, t2, t3));
  45. }
  46. public bool Register(Guid id)
  47. {
  48. try
  49. {
  50. if (!_callbackClientList.ContainsKey(id))
  51. {
  52. LOG.Info(string.Format("客户端{0}已连接", id.ToString()), true);
  53. }
  54. _callbackClientList[id] = OperationContext.Current.GetCallbackChannel<IEventServiceCallback>();
  55. }
  56. catch (Exception ex)
  57. {
  58. LOG.Error("监听事件发生错误", ex);
  59. }
  60. return true;
  61. }
  62. public void UnRegister(Guid id)
  63. {
  64. if (!_callbackClientList.ContainsKey(id))
  65. {
  66. LOG.Info(string.Format("客户端{0}断开连接", id.ToString()), true);
  67. }
  68. IEventServiceCallback service;
  69. _callbackClientList.TryRemove(id, out service);
  70. }
  71. }
  72. }