QueueBackgroundWorkItem 实际上是否在排队后台工作?

Does QueueBackgroundWorkItem actually queue background work?

我们正在 运行 宁 ASP.NET WebAPI 2 服务,我们想用我们的记录器记录一些请求到 email/database。

因为它是后台工作,而且因为在 asp.net 中我认为我们应该在后台使用 HostingEnvironment.QueueBackgroundWorkItem 到 运行 它。

我希望我的日志全部有序 - 令我惊讶的是,我找不到任何表明 QueueBackgroundWorkItem 实际上保证排队的工作项目 运行 有序或表明它不.

所以,我的问题是:QueueBackgroundWorkItem 是否保证排队的工作按顺序执行?

 HostingEnvironment.QueueBackgroundWorkItem((e) => Console.WriteLine("A")); 
 HostingEnvironment.QueueBackgroundWorkItem((e) => Console.WriteLine("B"));

我知道上面代码片段的输出总是:

A
B

还是会出问题?

QueueBackgroundWorkItem 保证排队的工作按顺序执行

引用自HostingEnvironment.QueueBackgroundWorkItem

New HostingEnvironment.QueueBackgroundWorkItem method that lets you schedule small background work items. ASP.NET tracks these items and prevents IIS from abruptly terminating the worker process until all background work items have completed. These will enable ASP.NET applications to reliably schedule Async work items.

文档中似乎没有任何合同内容。

查看参考源,似乎使用了一个名为 BackgroundWorker 的 class 来实际执行这些任务。

反过来,这似乎是 运行 ThreadPool 上的任务,并且明确可能正在并行执行多个任务:

    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);
    }

所以我想说,假设两个排队的任务将完成的顺序是不安全的。