MegaBites-AI/Windows-powershell
0372
1// Licensed to the .NET Foundation under one or more agreements.2// The .NET Foundation licenses this file to you under the MIT license.3 4using System;5using System.Collections.Generic;6using System.Runtime.InteropServices;7using System.Management.Automation.InteropServices;8 9namespace System.Management.Automation.ComInterop10{11 /// <summary>12 /// ComEventSinksContainer is just a regular list with a finalizer.13 /// This list is usually attached as a custom data for RCW object and14 /// is finalized whenever RCW is finalized.15 /// </summary>16 internal class ComEventSinksContainer : List<ComEventsSink>, IDisposable17 {18 private ComEventSinksContainer()19 {20 }21 22 private static readonly object s_comObjectEventSinksKey = new object();23 24 public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool createIfNotFound)25 {26 object data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey);27 if (data != null || !createIfNotFound)28 {29 return (ComEventSinksContainer)data;30 }31 32 lock (s_comObjectEventSinksKey)33 {34 data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey);35 if (data != null)36 {37 return (ComEventSinksContainer)data;38 }39 40 ComEventSinksContainer comEventSinks = new ComEventSinksContainer();41 if (!Marshal.SetComObjectData(rcw, s_comObjectEventSinksKey, comEventSinks))42 {43 throw Error.SetComObjectDataFailed();44 }45 46 return comEventSinks;47 }48 }49 50 #region IDisposable Members51 52 public void Dispose()53 {54 DisposeAll();55 GC.SuppressFinalize(this);56 }57 58 #endregion59 60 private void DisposeAll()61 {62 foreach (ComEventsSink sink in this)63 {64 ComEventsSink.RemoveAll(sink);65 }66 }67 68 ~ComEventSinksContainer()69 {70 DisposeAll();71 }72 }73}74 