Difference between HostingEnvironment.QueueBackgroundWorkItem and HostingEnvironment.RegisterObject

I am currently using HostingEnvironment.RegisterObject to run my background work in my MVC 5 application. In particular, I,

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

using,

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

So using HostingEnvironment.QueueBackgroundWorkItem takes precedence over HostingEnvironment.RegisterObject

+6
source share
1 answer

QueueBackgroundWorkItem is actually just an illustrious call to RegisterObject under covers. It handles the conversion of a call to Stop to a CancellationToken, which can be used by asynchronous work items, and is recorded in the event log in case of failures and several other accounting items. There is nothing to worry about. You can use Reflector or ILSpy to view the source until http://referencesource.microsoft.com/ is updated with sources 4.5.2.

If you like the complexity of doing all the accounting work, there is no reason why you will not be able to continue using RegisterObject . The new API is for consumers who want something simpler.

+7
source

Source: https://habr.com/ru/post/970141/


All Articles