Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Event handler is getting called twice?

Tags:

c#

.net

events

I've created an event handler that simply returns a list of objects that I receive from a web service when the call completes.

Now I went ahead and ran the app in debug mode and found out that the first time the event is called it works perfectly, but immediately after it completes the event is being fired for a second time. I've checked and am absolutely sure I am not calling the event more than once in the receiver class.

This is my first shot at creating custom event handlers inside my applications so I am not entirely sure the implementation is 100% accurate.

Any ideas of what might be causing this? Is the way I created the event handler accurate?

This is the DataHelper class

public class DataHelper
{
    public delegate void DataCalledEventHandler(object sender, List<DataItem> dateItemList);
    public event DataCalledEventHandler DataCalled;

    public DataHelper()
    {

    }

    public void CallData()
    {
        List<DataItem> dataItems = new List<DataItem>();
        //SOME CODE THAT RETURNS DATA
        DataCalled(this, dataItems);
    }
}

This is where I subscribed to my event:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
   GetNewDataItems();
}
private void GetNewDataItems()
        {

                try
                {
                    DataHelper dataHelper = new DataHelper();
                    dataHelper.CallData();
                    dataHelper.DataCalled += new DataHelper.DataCalledEventHandler(dataHelper_DataCalled);

                }
                catch
                {
                   //Handle any errors
                }
            }
    }

    void dataHelper_DataCalled(object sender, List<DataItem> dataItemsList)
    {
        //Do something with results
        //NOTE: THIS IS WHERE THE EXCEPTION OCCURS WHEN EVENT IS FIRED FOR SECOND TIME
    }
like image 677
Edward Avatar asked Nov 05 '11 14:11

Edward


People also ask

How do I use custom events in a JavaScript application?

To show how to use custom events in a JavaScript application, we’ll build a simple app that allows users to add a profile and automatically get a profile card. Here is what the page will look like when we’re done: Create a folder, name it anything you like, and create an index.html file in the folder. Add the following to index.html:

How do I get the data from a custom event?

Data can only be gotten from the event’s target. A custom event can be created using the CustomEvent constructor: As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor. The only difference is in the object passed as the second parameter to the constructor.

What is the difference between event and event constructor in Java?

The only difference is in the object passed as the second parameter to the constructor. When creating events with the Event constructor, we were limited by the fact that we can’t pass data through the event to the listener.

How do I create a custom event in Salesforce?

A custom event can be created using the event constructor, like this: In the above snippet, we created an event, myevent, by passing the event name to the Event constructor. Event names are case-insensitive, so myevent is the same as myEvent and MyEvent, etc. We made a custom demo for . No really. Click here to check it out.


1 Answers

Probably you added the delegate twice, is it possible?

In this case the problem is not in who calls the delegate but in who adds the delegate to the event.

Probably you did something like...

private Class1 instance1;

void callback(...)
{
}

void myfunction()
{
    this.instance1.DataCalled += this.callback;
    this.instance1.DataCalled += this.callback;
}

If not, try to add a breakpoint where you subscribe to the event and see if it is called twice.

As a side note, you should always check for null when calling an event, if there is no subscriber you can get a NullReferenceException. I would also suggest you to use a variable to store the event delegate to avoid the risk of multithreading failure.

public void CallData()
{
    List<DataItem> dataItems = new List<DataItem>();
    var handler = this.DataCalled;
    if (handler != null)
        handler(this, dataItems);
}

Edit: since now I see the code, is obvious that each time you call the GetNewDataItems method you are subsribing every time to the event. Do in such a way you subscribe only once, for example, in constructor, or store your variable somewhere or deregister the event when you finish.

This code contains also a probable memory leak: every time you add a delegate you keep alive both the instance that contains the event and the instance that contains the subscribed method, at least, until both are unreferenced.

You can try to do something like this...

void dataHelper_DataCalled(object sender, List<DataItem> dataItemsList)
{
    // Deregister the event...
    (sender as Class1).DataCalled -= dataHelper_DataCalled; 

    //Do something with results
}

In this way however you must ensure that if there is not an exception during the event registration the event will be fired or you have again memory leaks.

Instead of an event perhaps you need just a delegate. Of course you should set your delegate field to null when you want to release the delegate.

// in data helper class

private DataHelper.DataCalledEventHandler myFunctor;

public void CallData(DataHelper.DataCalledEventHandler functor)
{
    this.myFunctor = functor;
    //SOME CODE THAT RETURNS DATA
}

// when the call completes, asynchronously...
private void WhenTheCallCompletes()
{
    var functor = this.myFunctor;
    if (functor != null)
    {
        this.myFunctor = null;
        List<DataItem> dataItems = new List<DataItem>();
        functor(this, dataItems);
    }
}
    
// in your function
...    dataHelper.CallData(this.dataHelper_DataCalled);    ...
like image 121
Salvatore Previti Avatar answered Sep 28 '22 09:09

Salvatore Previti