ml123
ml123

Reputation: 1251

Using Task within QueueBackgroundWorkItem

I was diving into the QueueBackgroundWorkItem class recently, and I've stumbled across samples I do not understand.

My understanding is that QueueBackgroundWorkItem creates a new thread, in which the given Action or Func is executed, and there is no need to manually create a new Thread or Task.

However, many samples I see create a new Task within the Action executed, like this one (copied from here):

using System.Web.Mvc;
using System.Web.Hosting;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System;

namespace MyApp.Controllers
{
public class HomeController : Controller
{
    public ActionResult Index()
    {
        //Sample 1
        //Action overload
        //with lambda expression
        HostingEnvironment.QueueBackgroundWorkItem(
            clt => LongRunningAction(clt)
        );

        //Sample 2
        //Action overload
        //without lambda expression
        HostingEnvironment.QueueBackgroundWorkItem(
            (Action)LongRunningAction
        );

        //Sample 3
        //Action overload
        //with lambda expression
        HostingEnvironment.QueueBackgroundWorkItem(
            clt => LongRunningActionAsync(clt)
        );

        //Sample 4
        //Action overload
        //without lambda expression
        HostingEnvironment.QueueBackgroundWorkItem(
            await (Action)LongRunningAction
        );

        return View();
    }

    //Action overload's target
    private void LongRunningAction(CancellationToken clt)
    {
        Task.Run(() => { Thread.Sleep(5000); 
                         Debug.WriteLine("Action executed"); 
                       });
    }

    //Action overload's target
    private async void LongRunningActionAsync(CancellationToken clt)
    {
        await Task.Run(() => { Thread.Sleep(5000); 
                               Debug.WriteLine("Action async executed"); 
                             });
    }
}
} 

So what's the point of having a Task.Run inside the Action?

Upvotes: 1

Views: 2300

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

Your understanding is correct. Internally, HostingEnvironment.QueueBackgroundWorkItem delegates the execution to the thread pool (after doing some various registration work to keep track of the execution), so there's no benefit to starting yet another thread inside of the action. It even defeats the whole purpose of HostingEnvironment.QueueBackgroundWorkItem, since the methods are asynchronous and yet don't return a Task, and therefore the execution won't be tracked by ASP.NET.

Upvotes: 1

Related Questions