gpt4 book ai didi

c# - HostingEnvironment.QueueBackgroundWorkItem 和 HostingEnvironment.RegisterObject 之间的区别

转载 作者:太空狗 更新时间:2023-10-29 21:27:41 31 4
gpt4 key购买 nike

目前我正在使用 HostingEnvironment.RegisterObject 在我的 MVC 5 应用程序中运行我的后台工作。具体来说,我有,

public class BackgroundWorker
{
/// <summary>
/// Runs a background task that is registered with the hosting environment
/// so it is guaranteed to finish executing.
/// </summary>
/// <param name="action">The lambda expression to invoke.</param>
public static void Run(Action action)
{
new IISBackgroundTask().DoWork(action);
}

/// <summary>
/// Generic object for completing tasks in a background thread
/// when the request doesn't need to wait for the results
/// in the response.
/// </summary>
class IISBackgroundTask : IRegisteredObject
{
/// <summary>
/// Constructs the object and registers itself with the hosting environment.
/// </summary>
public IISBackgroundTask()
{
HostingEnvironment.RegisterObject(this);
}

/// <summary>
/// Called by IIS, once with <paramref name="immediate"/> set to false
/// and then again with <paramref name="immediate"/> set to true.
/// </summary>
void IRegisteredObject.Stop(bool immediate)
{
if (_task.IsCompleted || _task.IsCanceled || _task.IsFaulted || immediate)
{
// Task has completed or was asked to stop immediately,
// so tell the hosting environment that all work is done.
HostingEnvironment.UnregisterObject(this);
}
}

/// <summary>
/// Invokes the <paramref name="action"/> as a Task.
/// Any exceptions are logged
/// </summary>
/// <param name="action">The lambda expression to invoke.</param>
public void DoWork(Action action)
{
try
{
_task = Task.Factory.StartNew(action);
}
catch (AggregateException ex)
{
// Log exceptions
foreach (var innerEx in ex.InnerExceptions)
{
Logger.Log(innerEx);
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
}

private Task _task;
private static readonly ILogger Logger = Loggers.Logger.Instance;
}
}

用法,

 BackgroundWorker.Run(() => 
BackGroundMethod();
);// run this in a background thread

因此,使用 HostingEnvironment.QueueBackgroundWorkItemHostingEnvironment.RegisterObject 有任何优势

最佳答案

QueueBackgroundWorkItem 实际上只是在幕后对 RegisterObject 的美化调用。它负责将对 Stop 的调用转换为可由异步工作项使用的 CancellationToken,在发生故障时写入事件日志,以及其他一些簿记项.没有什么特别有趣的。您可以使用 Reflector 或 ILSpy 浏览源代码直到 http://referencesource.microsoft.com/使用 4.5.2 源更新。

如果您对自己执行所有簿记的复杂性感到满意,那么您没有理由不继续使用 RegisterObject。新的 API 适用于想要更简单一些的消费者。

关于c# - HostingEnvironment.QueueBackgroundWorkItem 和 HostingEnvironment.RegisterObject 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23978511/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com