user3953989
user3953989

Reputation: 1941

Will BeginInvoke continue to execute if I return immediately from an MVC controller action?

I'm trying to troubleshoot an issue where we believe an Async call may not execute in some instances.

delegate void TestDelegate();
void doWork()
{
    Thread.Sleep(5000);
}
public ActionResult Test()
{
    var myAsyncCall = new TestDelegate(doWork);
    myAsyncCall.BeginInvoke();
    return View();
}

Upvotes: 1

Views: 575

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564821

In general, you need to call EndInvoke on the delegate. This will allow you to determine why things are not working (like an exception being raised within doWork, which would explain the described issue).

For details, see Calling Synchronous Methods Asynchronously on MSDN.

That being said, I would recommend reworking this to use the the TPL instead of delegate.BeginInvoke, as it makes some of the checking simpler overall. You could write the above as:

public ActionResult Test()
{
    // Start the async work, and attach a continuation which happens if exceptions occur
    Task.Run(() => doWork())
    .ContinueWith(t =>
    {
       var ex = t.Exception.InnerException;
       LogException(ex);
    }, TaskContinuationOptions.OnlyOnFaulted);

    return View();
}

Upvotes: 2

Related Questions