在QueueBackgroundWorkItem中使用Task

时间:2016-05-29 16:53:32

标签: c# asp.net multithreading

我最近刚进入QueueBackgroundWorkItem课程,我偶然发现了我不理解的样本。

我的理解是QueueBackgroundWorkItem创建了一个新线程,其中执行了给定的ActionFunc,并且无需手动创建新的线程或任务。 / p>

但是,我看到的很多样本在Action中执行了一个新的Task,就像这个(从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"); 
                             });
    }
}
} 

那么在Action中有一个Task.Run是什么意思?

1 个答案:

答案 0 :(得分:1)

您的理解是正确的。在内部,public function fire_db($currentUserID, $id_staff){ $this->db->where('id_player', $currentUserID); $this->db->where('id_hired_staff', $id_staff); $this->db->limit(1); $this->db->delete('game_hired_staff'); if ($this->db->num_rows() == 1) { return true; } else return false; } 将执行委托给线程池(在执行一些不同的注册工作以跟踪执行之后),因此在操作中启动另一个线程没有任何好处。 它甚至违背了HostingEnvironment.QueueBackgroundWorkItem的整个目的,因为这些方法是异步的,但是不返回任务,因此ASP.NET不会跟踪执行。