Neil Knight
Neil Knight

Reputation: 48597

Which thread does the callback run on?

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 BeginInvokemethod was using?

Upvotes: 2

Views: 373

Answers (1)

Ani
Ani

Reputation: 113472

From MSDN:

Executing a Callback Method When an Asynchronous Call Completes

[...] The callback method is executed on a ThreadPool thread.

Upvotes: 2

Related Questions