简体   繁体   中英

Wp8 - EventHandler is null when redirected from app and back

In my application I have simple EventHandler (in my ViewModel) defined as this :

public event EventHandler FavouriteChangedEvent;

Then when I need, I fire the event with this

FavouriteChangedEvent(this, null);

Everything is working as expected, however in my app, there are clickable links, which opens webbrowser (as separate app). When you go back to the application, then when I try to run FavouriteChangedEvent(this, null); it ends with NullPointerException (From debugging it is beacause FavouriteChangedEvent is really null).

Why is that?

I find this on the internet and used it

    public delegate void EventHandler(object sender, string myValue);
    public event EventHandler FavouriteChangedEvent = delegate { }; 

But it does not help much. The application does not fall, but in my View class, I have this line in constructor _dataContext.FavouriteChangedEvent += _dataContext_FavouriteChangedEvent;

After go out and back to the app, this event is not triggered anymore.

Then when I need, I fire the event with this

FavouriteChangedEvent(this, null);

it ends with NullPointerException (From debugging it is beacause FavouriteChangedEvent is really null

This is because there are no event handlers yet .

The event is a class

Once a class has declared an event, it can treat that event just like a field of the indicated delegate type. The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a delegate that should be called when the event is invoked. Thus, invoking an event is generally done by first checking for null and then calling the event.

You have to at least check for null before rising event:

if(FavouriteChangedEvent != null)
    FavouriteChangedEvent(this, null);

Note, to make this thread-safe you will have to copy event to local variable, to ensure what null check and rising occurs for the same event:

var event = FavouriteChangedEvent;
if(event != null)
    event(this, null);

Described solution (with attaching empty delegate on constructing) is another possible thread-safe solution.

According to event design guidelines :

DO use a protected virtual method to raise each event

This said - do not rise event handler like this, but call protected virtual method (called OnFavouriteChangedEvent ) which will rise event. And there is no need to include word "event" into event name. Make it simple: FavouriteChanged .

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