2015-02-02 4 views
0

코드 :여러 비동기 작업과 대표

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을 호출합니다.

문제 :

당신이 볼 수 있듯이, _notDelEndInvokedelegate 나중에에 사용되는 전역 변수입니다.

". 이 위양 일치하지 않는 제공 된 IAsyncResult 개체"문제는 두 번째 Notifications 호출 후, 객체가 나에게 말한다 오류를주고, 더 이상 같은되지 않는 것입니다

+0

왜 '_notDel'이 글로벌입니까? 인스턴스별로 만들 수 있습니까? 이 작업을 위해 각 대리자 인스턴스를 캡슐화해야합니다. –

+1

나중에 사용하기 위해 상태 매개 변수로 전달되는 필드로 대리자를 보유하는 일시적인 개체가 필요합니다. –

+0

@YuvalItzchakov'CallBackNotification' 내부에서 어떻게'EndInvoke'를 할 수 있습니까? –

답변

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