2011-10-25 161 views
2

我寫了一個小應用程序,使用BeginInvoke調用異步方法。該回調的哪個線程運行?

// Asynchronous delegate 
Func<int, MailItemResult> method = SendMail; 

// Select some records from the database to populate col 

while (i < col.Count) 
{ 
    method.BeginInvoke(i, SendMailCompleted, method); 
    i++; 
} 

Console.ReadLine(); 

這是控制檯應用程序的Main()方法。 MailItemResult被定義爲:

class MailItemResult 
{ 
    public int CollectionIndex { get; set; } 
    public bool Success { get; set; } 
    public DateTime DateUpdated { get; set; } 
} 

不錯,簡單。和回調方法定義如下:

static void SendMailCompleted(IAsyncResult result) 
{ 
    var target = (Func<int, MailItemResult>)result.AsyncState; 
    MailItemResult mir = target.EndInvoke(result); 
    if (mir.Success) 
    { 
     // Update the record in the database 
    } 
} 

此應用程序在首次運行100ish線程,然後在數據庫中拋出了一個僵局。現在,我理解了死鎖,但是我在這個小應用程序中無法理解的是哪個線程是被調用的回調方法(SendMailCompleted)?這是從主應用程序線程中調用的嗎?還是使用線程池中的相同線程,BeginInvoke方法正在使用?

+0

可能的重複:http://stackoverflow.com/q/5531098/210709 – IAbstract

回答

2

MSDN

執行的回調方法當異步調用完成

[...]回調方法在一個線程池的線程執行。

相關問題