Give background threads time to complete in IIS

Thanks to this post

public sealed class OutOfProcessMediatorDecorator<TCommand> :
    IMediatingHandler<TCommand>, IRegisteredObject where TCommand : IMediator
{
    private readonly IMediatingHandler<TCommand> decorated;
    private readonly Container container;

    public OutOfProcessMediatorDecorator(
        IMediatingHandler<TCommand> decorated,
        Container container)
    {
        this.decorated = decorated;
        this.container = container;
    }

    public void Execute(TCommand command)
    {
        HostingEnvironment.RegisterObject(this);
        var task = Task.Factory.StartNew(() => 
            {
                using(container.BeginLifetimeScope())
                {
                    try
                    {
                        this.decorated.Execute(command);
                    }
                    finally
                    {
                        HostingEnvironment.UnregisterObject(this);
                    }
                }
            });
    }

    void IRegisteredObject.Stop(bool immediate)
    {
        // we do nothing here as the object is not long lived
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.