C#无法使用Task返回类型方法委托事件处理程序

时间:2018-05-05 08:40:38

标签: c# reflection task

我正在努力进行自定义异步事件域处理 我尝试为 Task HandleEvent(TEvent @event) 方法创建委托 - 负责异步执行事件,一旦返回类型为Task,那么我有

的例外
  

System.ArgumentException:'无法绑定到目标方法,因为   它的签名或安全透明度与其不相容   代表类型。'

public IDisposable RegisterHandler(object handler)
        {
            Contract.Requires(handler != null);

            var interfaceType = handler.GetType().GetTypeInfo().GetInterfaces()
                .SingleOrDefault(t => t.GetGenericTypeDefinition() == typeof(IEventHandler<>));

            if (interfaceType == null)
            {
                throw new ArgumentException(string.Format("Supplied parameter does not implement {0} interface.", nameof(IEventHandler<object>)));
            }

            var eventType = interfaceType.GenericTypeArguments[0];

            var stream = this.eventStreams[eventType];
            var streamType = stream.GetType();

            if (this.eventStreams == null)
            {
                throw new KeyNotFoundException(string.Format("Event stream for '{0}' was not found.", eventType.Name));
            }

            var handleEvent = handler.GetType().GetTypeInfo().GetMethod(nameof(IEventHandler<object>.HandleEvent));
            var actionType = typeof(Action<>).MakeGenericType(eventType);

            var del = handleEvent.CreateDelegate(actionType, handler);

            var method = streamType.GetTypeInfo().GetMethods().First(
                t =>
                    t.Name == nameof(IEventStream<object>.Subscribe) &&
                    t.GetParameters().FirstOrDefault()?.ParameterType.GetGenericTypeDefinition() == typeof(Action<>));

            return (IDisposable)method.Invoke(stream, new object[] { del });
        }

如何为相关方法创建委托?

0 个答案:

没有答案