使用代理的多个异步操作

时间:2015-02-02 12:28:15

标签: c# asynchronous .net-4.0 delegates

代码:

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

预期行为:

只要公司符合截止日期,就会调用Notifications方法。在初始化期间,方法为每个公司循环并在该循环内调用Notifications

问题:

如您所见,_notDel是一个全局变量,稍后会用于EndInvoke delegate。问题是在第二次Notifications调用之后,对象不再相同,给出了错误说明:

" 提供的IAsyncResult对象与此委托不匹配。"

1 个答案:

答案 0 :(得分:1)

只需将notDel作为BeginInvoke的最后一个参数传递,然后使用r.AsyncState获取源代理。

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