Task.Run vs ThreadPool.QueueUserWorkItem

前端 未结 2 1176
时光说笑
时光说笑 2021-02-01 14:40

Not a subject expert I\'m trying to understand more of the async world available in .NET. Task.Run and ThreadPool.QueueUserWorkItem both allow dispatching work on a pool thread

2条回答
  •  一个人的身影
    2021-02-01 15:31

    ThreadPool.QueueUserWorkItem is just the older implementation (introduced in .NET 1.1) of doing the same job as Task.Run (introduced in .NET 4.5).

    Microsoft tries to avoid breaking backwards compatibility in .NET. Something written for .NET 1.1 can be compiled and ran in .NET 4.5 with (usually) no changes. Breaking changes are usually from compiler changes, not framework changes, like the variable declared in a foreach used inside a lambada behaving differently in C# 5 and newer.

    There is no real reason to use ThreadPool.QueueUserWorkItem when you have Task.Run.

    One ending point: ironically, things have actually come full circle with HostingEnvironment.QueueBackgroundWorkItem(...). It lets you run something on a background thread in a ASP.NET environment and let the background work be notified of AppDomain shutdowns by the web server (which can frequently happen during long periods of inactivity).

提交回复
热议问题