Tuesday, 28 November 2017

Unity and HTTP non-blocking long-term running tasks in Web API

If to continue discussing UNITY we can take a look at the corresponding challenging task ;)

So, we need release UI thread and return to the user message that "long running task started" and at the same time logic must be executing in background.

According to our approach described in the previous article we know that during each controller creation dependency resolver calls BeginScope() and created scope stores all references for instances that needed for resolving any type according to defined UNITY settings for types.

And it's important to write that stuff correctly.

Following code will raise exception "Entity framework DbContext already disposed".


[HttpPost]
[Route("MyAction")]
[AllowAnonymous]
public async Task ReleasingUIThreadOnLongRunningExecution()
{
     await handler.Execute();
     return Ok("My long running execution started");
}

The reason is that after the action executed the scope will be disposed and all instances in it will disposed too.

Here you can see right solution.

  • We get a thread from ThreadPool and assign work to it
  • We create new scope
  • Resolve our handler
  • Execute it
  • Dispose scope


        [HttpPost]
        [Route("MyAction")]
        [AllowAnonymous]
        public async Task ReleasingUIThreadOnLongRunningExecution()
        {
            System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(
             async ct =>
            {
                using (var scope
                      = GlobalConfiguration.Configuration
                              .DependencyResolver.BeginScope())
                {
                    var handler = scope.GetService(typeof(MyLogicHandler)) 
                       as MyLogicHandler;

                    if (handler != null)
                    {
                        await handler.Execute();
                    }
                }
            });

            return Ok("My long running execution started");
        }

No comments:

Post a Comment