简体   繁体   中英

WeakEventManager - event handler is not called

I am not able to reproduce the issue (and project is too big to post it here, plus I am not sure what are related parts to post) and I need ideas of what could go wrong here.

I have abstract class with static event

public abstract partial class A : Base
{
    public static event EventHandler Test;
    public static void OnTest() => Test?.Invoke(null, EventArgs.Empty);
}

Then I subscribe to this event normally and using WeakEventManager :

A.Test += (s, e) => { };
WeakEventManager<A, EventArgs>.AddHandler(null, nameof(A.Test), (s, e) => { });

And for some reasons weak event handler doesn't get fired when OnTest() is called. Everything (invoke and handlers) are operating in the UI thread.

I've set breakpoints:

  1. On AddHandler() , it runs and the instance of class then persist.
  2. On Invoke() , it runs when OnTest is called, I can see 2 subscribers if I call Test.GetInvocationList() one of them is DeliverEvent() from WeakEventManager , so event was registered and Invoke() should call weak event handler.
  3. Inside normal event handler, it runs.
  4. Inside weak event handler, nothing , this breakpoint never get hit.

Any ideas of why would this occur or what should I investigate?


I've tried to look into .net sources , to find answers there, but there is ProtectedAddHandler which sources I can't find... I found it , but what is the next? Abstract method, who implements it?...

WeakEventManager ... not working event handler ...

To whoever face this issue, the problem is this: you must rise static event with null as sender ! Eg in my case it was (use this to reproduce issue with code in the question):

public static void OnTest() => Test?.Invoke("whatever", EventArgs.Empty);

This case will be handled by normal subscriber without any problem.

But in case of WeakEventManager it must be a null (special case), otherwise your event handler will not work.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM