0

Code:

private delegate void NotificationDelegate(sis_company company, int days, string type, string param);

private NotificationDelegate _notDel;

private void Notifications(sys_company company, int days, string type, string param)
{
    if (*something*)
    {
        _notDel = SendEmails;
        _notDel.BeginInvoke(company, days, type, param, CallBackNotification, null);
    }
}

private void SendEmails(sys_company company, int days, string type, string param)
{
    //Here I'll send all e-mails.
}

private void CallBackNotification(IAsyncResult r)
{
    if (this.IsDisposed) return;

    try
    {
        _notDel.EndInvoke(r);
    }
    catch (Exception ex)
    {
        LogWriter.Log(ex, "EndInvoke Error");
    }
}

Expected Behaviour:

The Notifications method is called whenever a company meets the deadline. During the initialization a method loops for each company and calls Notifications inside that loop.

Problem:

As you can see, _notDel is a global variable, used later on to EndInvoke the delegate. The problem is that after the second Notifications call, the object is not the same anymore, giving me the error that says:

"The IAsyncResult object provided does not match this delegate."

8
  • Why is _notDel global? Can you make it per instance? You have to encapsulate each delegate instance for this to work Commented Feb 2, 2015 at 12:33
  • 1
    You simply need a transient object which holds the delegate as a field which is passed as a state parameter for later use. Commented Feb 2, 2015 at 12:34
  • @YuvalItzchakov How can I EndInvoke inside the CallBackNotification? Commented Feb 2, 2015 at 12:34
  • Show us the declaration of the class Commented Feb 2, 2015 at 12:35
  • 1
    Just pass your _notDel as the last parameter for BeginInvoke and use r.AsyncState to get the source delegate then Commented Feb 2, 2015 at 12:36

1 Answer 1

1

Just pass your notDel as the last parameter for BeginInvoke and use r.AsyncState to get the source delegate then.

//Call like this:

NotificationDelegate notDel = Notifications;
notDel.BeginInvoke(company, days, type, param, CallBackNotification, notDel);

//And inside the CallBack:

var del = r.AsyncState as NotificationDelegate;

if (del != null)
    del.EndInvoke(r);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.