与委托的多个异步操作
Multiple Async Operations with 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 对象与此委托不匹配。"
只需将您的 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);
代码:
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 对象与此委托不匹配。"
只需将您的 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);