/// <summary> /// Open a channel to receive a message. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TMessage">The type of the message.</typeparam> /// <param name="key">Specify a key to limit the channels to receive the message.</param> /// <param name="method">The delegate that is called when the message is sent.</param> /// <param name="weakReference">The weak reference of the object.<br/> /// The channel will be automatically closed when the object is garbage collected.<br/> /// To achieve maximum performance, you can set this value to null (DON'T forget to close the channel manually).</param> /// <returns>A new instance of XChannel.<br/> /// You need to call <see cref="XChannel.Dispose()"/> when the channel is no longer necessary, unless the weak reference is specified.</returns> public static XChannel OpenKey <TKey, TMessage>(TKey key, Action <TMessage> method, object?weakReference = null) where TKey : notnull { var collection = Cache_KeyMessage <TKey, TMessage> .Collection; if (collection.CleanupCount++ >= CrossChannelConst.CleanupDictionaryThreshold) { lock (collection) { collection.CleanupCount = 1; collection.Cleanup(); } } var channel = new XChannel_KeyMessage <TKey, TMessage>(collection, key, weakReference, method); return(channel); }
/// <summary> /// Open a channel to receive a message. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TMessage">The type of the message.</typeparam> /// <param name="key">Specify a key to limit the channels to receive the message.</param> /// <param name="method">The delegate that is called when the message is sent.</param> /// <param name="weakReference">The weak reference of the object.<br/> /// The channel will be automatically closed when the object is garbage collected.<br/> /// To achieve maximum performance, you can set this value to null (DON'T forget to close the channel manually).</param> /// <returns>A new instance of XChannel.<br/> /// You need to call <see cref="XChannel.Dispose()"/> when the channel is no longer necessary, unless the weak reference is specified.</returns> public XChannel OpenKey <TKey, TMessage>(TKey key, Action <TMessage> method, object?weakReference = null) where TKey : notnull { var collection = (XCollection_KeyMessage <TKey, TMessage>) this.dictionaryKeyMessage.GetOrAdd( new Identifier_KeyMessage(typeof(TKey), typeof(TMessage)), x => new XCollection_KeyMessage <TKey, TMessage>()); if (collection.CleanupCount++ >= CrossChannelConst.CleanupDictionaryThreshold) { lock (collection) { collection.CleanupCount = 1; collection.Cleanup(); } } var channel = new XChannel_KeyMessage <TKey, TMessage>(collection, key, weakReference, method); return(channel); }