简体   繁体   中英

Multiple Async Operations with Delegates

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 ."

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);

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