代码:
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对象与此委托不匹配。"
答案 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);