如从托管环境源代码中可以看出,QueueBackgroundWorkItem方法使用了_BackGroundWorkScheduler字段,该字段是BackgroundWorkScheduler类型的,用于调度后台工作项:
public sealed class HostingEnvironment : MarshalByRefObject {
private static HostingEnvironment _theHostingEnvironment;
private BackgroundWorkScheduler _backgroundWorkScheduler = null;
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public static void QueueBackgroundWorkItem(Action<CancellationToken> workItem) {
if (workItem == null) {
throw new ArgumentNullException("workItem");
}
QueueBackgroundWorkItem(ct => { workItem(ct); return _completedTask; });
}
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public static void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem) {
if (workItem == null) {
throw new ArgumentNullException("workItem");
}
if (_theHostingEnvironment == null) {
throw new InvalidOperationException();
}
_theHostingEnvironment.QueueBackgroundWorkItemInternal(workItem);
}
private void QueueBackgroundWorkItemInternal(Func<CancellationToken, Task> workItem) {
Debug.Assert(workItem != null);
BackgroundWorkScheduler scheduler = Volatile.Read(ref _backgroundWorkScheduler);
if (scheduler == null) {
BackgroundWorkScheduler newlyCreatedScheduler = new BackgroundWorkScheduler(UnregisterObject, Misc.WriteUnhandledExceptionToEventLog);
scheduler = Interlocked.CompareExchange(ref _backgroundWorkScheduler, newlyCreatedScheduler, null) ?? newlyCreatedScheduler;
if (scheduler == newlyCreatedScheduler) {
RegisterObject(scheduler);
}
}
scheduler.ScheduleWorkItem(workItem);
}
如果我们查看BackgroundWorkScheduler类的源代码:
internal sealed class BackgroundWorkScheduler : IRegisteredObject {
//....
public void ScheduleWorkItem(Func<CancellationToken, Task> workItem) {
Debug.Assert(workItem != null);
if (_cancellationTokenHelper.IsCancellationRequested) {
return; // we're not going to run this work item
}
// Unsafe* since we want to get rid of Principal and other constructs specific to the current ExecutionContext
ThreadPool.UnsafeQueueUserWorkItem(state => {
lock (this) {
if (_cancellationTokenHelper.IsCancellationRequested) {
return; // we're not going to run this work item
}
else {
_numExecutingWorkItems++;
}
}
RunWorkItemImpl((Func<CancellationToken, Task>)state);
}, workItem);
}
//other methods
}
我们可以注意到它内部使用了Asp.Net线程池来调度工作项。