c# – 在排队的后台工作项中保留主体

前端之家收集整理的这篇文章主要介绍了c# – 在排队的后台工作项中保留主体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用ASP.Net Web API 2 / .Net 4.5.2.

我在排队后台工作项时试图保留调用主体.为此,我试图:

Thread.CurrentPrincipal = callingPrincipal;

但是当我这样做时,我得到一个ObjectDisposedException:

System.ObjectDisposedException: Safe handle has been closed

如何将当前主体保留在后台工作项中?
我可以以某种方式复制校长吗?

public void Run<T>(Action<T> action)
{
    _logger.Debug("Queueing background work item");
    var callingPrincipal = Thread.CurrentPrincipal;
    HostingEnvironment.QueueBackgroundWorkItem(token =>
    {
        try
        {
            // UNCOMMENT - THROWS EXCEPTION
            // Thread.CurrentPrincipal = callingPrincipal;
            _logger.Debug("Executing queued background work item");
            using (var scope = DependencyResolver.BeginLifetimeScope())
            {
                var service = scope.Resolve<T>();
                action(service);
            }
        }
        catch (Exception ex)
        {
            _logger.Fatal(ex);
        }
        finally
        {
            _logger.Debug("Completed queued background work item");
        }
    });
}

解决方法

事实证明,ClaimsPrincipal现在有一个复制构造函数.
var principal = new ClaimsPrincipal(Thread.CurrentPrincipal);

这似乎可以在保留所有身份和声明信息的同时解决问题.完整的功能如下:

public void Run<T>(Action<T> action)
{
    _logger.Debug("Queueing background work item");
    var principal = new ClaimsPrincipal(Thread.CurrentPrincipal);

    HostingEnvironment.QueueBackgroundWorkItem(token =>
    {
        try
        {
            Thread.CurrentPrincipal = principal;
            _logger.Debug("Executing queued background work item");
            using (var scope = DependencyResolver.BeginLifetimeScope())
            {
                var service = scope.Resolve<T>();
                action(service);
            }
        }
        catch (Exception ex)
        {
            _logger.Fatal(ex);
        }
        finally
        {
            _logger.Debug("Completed queued background work item");
        }
    });
}

猜你在找的C#相关文章