回调在哪个线程上运行?
我编写了一个使用 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
}
}
该应用程序运行前 100 个线程,然后在数据库中引发死锁。现在,我理解了死锁,但在这个小应用程序中我无法理解的是回调方法 (SendMailCompleted
) 是在哪个线程中被调用的?这是从主应用程序线程调用的吗?或者它是否使用线程池中 BeginInvoke
方法所使用的同一线程?
I've written a small application that calls an Asynchronous method using 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();
This is in the Main()
method of a Console Application. MailItemResult
is defined as:
class MailItemResult
{
public int CollectionIndex { get; set; }
public bool Success { get; set; }
public DateTime DateUpdated { get; set; }
}
Nice and simple. And the callback method is defined as follows:
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
}
}
This application runs for the first 100ish threads and then throws up a deadlock in the database. Now, I understand deadlocks, but what I'm failing to understand in this small application is in which thread is the callback method (SendMailCompleted
) being called? Is this called from the main application thread? Or is it using the same thread, from the thread pool, that the BeginInvoke
method was using?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 MSDN:
From MSDN: