Receiver.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using NamedPipe.Communication;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.ServiceModel;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace NamedPipe
  9. {
  10. public class Receiver : IDisposable
  11. {
  12. public const String DefaultPipeName = "Pipe1";
  13. private PipeService _ps = new PipeService();
  14. private ServiceHost _host = null;
  15. private Boolean _operational { get; set; }
  16. #region PipeName
  17. private String _PipeName = String.Empty;
  18. /// <summary>
  19. /// Gets the name of the pipe being used by this reciever
  20. /// </summary>
  21. public String PipeName
  22. {
  23. get { return _PipeName; }
  24. }
  25. #endregion
  26. public Receiver(Action<String> messageReceivedAction) : this(DefaultPipeName, messageReceivedAction) { }
  27. public Receiver(String pipeName, Action<String> messageReceivedAction)
  28. {
  29. _PipeName = pipeName;
  30. _ps.MessageReceived = messageReceivedAction;
  31. }
  32. /// <summary>
  33. /// Stops the hosting service
  34. /// </summary>
  35. public void ServiceOff()
  36. {
  37. if (_host == null)
  38. { return; } //already turned off
  39. if (_host.State != CommunicationState.Closed)
  40. { _host.Close(); }
  41. _operational = false;
  42. }
  43. /// <summary>
  44. /// Performs the act of starting the WCF host service
  45. /// </summary>
  46. /// <returns>true, upon success</returns>
  47. public Boolean ServiceOn()
  48. {
  49. try
  50. {
  51. _host = new ServiceHost(_ps, new Uri(PipeService.URI));
  52. _host.AddServiceEndpoint(typeof(IPipeService), new NetNamedPipeBinding(), _PipeName);
  53. _host.Open();
  54. _operational = true;
  55. }
  56. catch (Exception ex)
  57. {
  58. _operational = false;
  59. }
  60. return _operational;
  61. }
  62. #region IDisposable
  63. //Read http://stackoverflow.com/a/538238/85297 for best practices regarding implementation of IDisposable
  64. ~Receiver()
  65. {
  66. Dispose(false);
  67. }
  68. public void Dispose()
  69. {
  70. Dispose(true);
  71. }
  72. private void Dispose(Boolean safeToDisposeManagedObjects)
  73. {
  74. if (safeToDisposeManagedObjects == false)
  75. { return; } //we have no unmaaged objects to worry about for purposes of this class
  76. _ps = null;
  77. }
  78. #endregion
  79. }
  80. }