【问题标题】:Fire and Forget with un-managed resources使用非托管资源一劳永逸
【发布时间】:2014-05-12 18:44:20
【问题描述】:

我在 owin 驱动的 web api 项目中使用 autofac。我已经到了一个需要“解雇并忘记”一些数据处理的地方。 这通常不是问题。但是由于依赖关系由 autofac 中间件管理的每个请求的生命周期范围控制。我无法在我未等待的 async 方法中使用非托管资源(这是我需要做的)。

//for example...
public async Task<IEnumerable<MyThings>> GetThings(){
     var things = await _thingRepo.GetInterestingThingsAsync();
     //fire and forget. -- not awaiting
     InjectedObject.DoThingsAsync(things);
     return things;
}

这里的问题是我需要使用DoThingsAsync内部的其他注入资源(非托管资源)。目前这会中断,因为它们会在 Owin 请求结束时被处理掉。

我可以为每个调用创建一个子生命周期范围,但我希望它们可能是一种更清洁的方式来做这些事情..

【问题讨论】:

标签: c# asp.net asp.net-web-api task autofac


【解决方案1】:

更新

随着 .Net Framework 4.5.2 的到来,我现在可以使用

HostingEnvironment.QueueBackgroundWorkItem 首选,因为它会阻止 IIS 在工作项完成之前回收。


我想我找到了适合我的用例的解决方案..

我只是在需要的地方注入这个类:

public class AsyncTask : IAsyncTask
{
    private ILifetimeScope _lifetimeScope;
    public AsyncTask(ILifetimeScope lifeTimeScope)
    {
        //disposed of by owning scope...
        _lifetimeScope = lifeTimeScope;
    }
    public async Task Fire<T>(Func<T,Task> asyncAction)
    {
        using (var scope = _lifetimeScope.BeginLifetimeScope())
        {
            await asyncAction(scope.Resolve<T>());
        }
    }
}
public interface IAsyncTask
{
    Task Fire<T>(Func<T, Task> action);
}

然后..

_asyncTask.Fire<IEmailService>(svc => svc.SendMillionsOfEmailsAsync(content));

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 2016-07-20
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多