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
方法正在使用?
可能的重複:http://stackoverflow.com/q/5531098/210709 – IAbstract