C# 回调在哪个线程上运行?
我编写了一个小应用程序,它使用C# 回调在哪个线程上运行?,c#,asynchronous,C#,Asynchronous,我编写了一个小应用程序,它使用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);
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();
又好又简单。回调方法定义如下:
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
}
}
static void SendMailCompleted(IAsyncResult结果)
{
var target=(Func)result.AsyncState;
MailItemResult mir=target.EndInvoke(结果);
如果(和平号成功)
{
//更新数据库中的记录
}
}
此应用程序运行前100个线程,然后在数据库中引发死锁。现在,我理解了死锁,但我在这个小应用程序中没有理解的是在哪个线程中调用回调方法(SendMailCompleted
)?这是从主应用程序线程调用的吗?或者它使用的是BeginInvoke
方法使用的线程池中的同一个线程?来自:
异步调用完成时执行回调方法
[…]回调方法在线程池线程上执行
可能的重复:
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
}
}