SafeConnectionPointCookie.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Runtime.ConstrainedExecution;
  4. using System.Runtime.InteropServices.ComTypes;
  5. using Microsoft.Win32.SafeHandles;
  6. namespace Standard;
  7. internal sealed class SafeConnectionPointCookie : SafeHandleZeroOrMinusOneIsInvalid
  8. {
  9. [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "IConnectionPoint")]
  10. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  11. public SafeConnectionPointCookie(IConnectionPointContainer target, object sink, Guid eventId) : base(true)
  12. {
  13. Verify.IsNotNull<IConnectionPointContainer>(target, "target");
  14. Verify.IsNotNull<object>(sink, "sink");
  15. Verify.IsNotDefault<Guid>(eventId, "eventId");
  16. this.handle = IntPtr.Zero;
  17. IConnectionPoint connectionPoint = null;
  18. try
  19. {
  20. target.FindConnectionPoint(ref eventId, out connectionPoint);
  21. int num;
  22. connectionPoint.Advise(sink, out num);
  23. if (num == 0)
  24. {
  25. throw new InvalidOperationException("IConnectionPoint::Advise returned an invalid cookie.");
  26. }
  27. this.handle = new IntPtr(num);
  28. this._cp = connectionPoint;
  29. connectionPoint = null;
  30. }
  31. finally
  32. {
  33. Utility.SafeRelease<IConnectionPoint>(ref connectionPoint);
  34. }
  35. }
  36. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  37. public void Disconnect()
  38. {
  39. this.ReleaseHandle();
  40. }
  41. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
  42. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  43. protected override bool ReleaseHandle()
  44. {
  45. bool result;
  46. try
  47. {
  48. if (!this.IsInvalid)
  49. {
  50. int dwCookie = this.handle.ToInt32();
  51. this.handle = IntPtr.Zero;
  52. try
  53. {
  54. this._cp.Unadvise(dwCookie);
  55. }
  56. finally
  57. {
  58. Utility.SafeRelease<IConnectionPoint>(ref this._cp);
  59. }
  60. }
  61. result = true;
  62. }
  63. catch
  64. {
  65. result = false;
  66. }
  67. return result;
  68. }
  69. private IConnectionPoint _cp;
  70. }