Task.Run vs. ContinueWith in ASP.NET MVC Task.Run vs. ContinueWith in ASP.NET MVC asp.net asp.net

Task.Run vs. ContinueWith in ASP.NET MVC


This is probably something specific to your web app, so I can only speculate, but here's what I think:

  • It should work if you do this:

    DoSomeBackgroundWork()    .ContinueWith(t => Debug.WriteLine("Background work finished"),         TaskContinuationOptions.ExecuteSynchronously);

    This would be more close to the Task.Run version, where the continuation runs synchronously.

  • Right before you call DoSomeBackgroundWork directly from the controller method, add this:

    Debug.WriteLine(new { TaskScheduler.Current });

    If the output is anything but ThreadPoolTaskScheduler, I might be able to further explain this behavior (as I've just dealt with a somewhat related problem here).

BTW, using fire-and-forget in ASP.NET like this is really not a good idea, there's a lot of questions on SO discussing this.