运行async方法作为Quartz.NET作业和处置对象问题

时间:2016-10-07 10:11:43

标签: c# entity-framework async-await quartz.net quartz.net-2.0

我在此上下文中使用Quartz.NET(需要提及的是GrabberContextDbContext扩展类):

// configuring Autofac:
var builder = new ContainerBuilder();

// configuring GrabberContext
builder.RegisterType<GrabberContext>()
    .AsSelf()
    .InstancePerLifetimeScope();

// configuring GrabService
builder.RegisterType<GrabService>()
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

// configuring Quartz to use Autofac
builder.RegisterModule(new QuartzAutofacFactoryModule());
builder.RegisterModule(new QuartzAutofacJobsModule(typeof(DiConfig).Assembly));

var container = builder.Build();

// configuring jobs:
var scheduler = container.Resolve<IScheduler>();
scheduler.Start();
var jobDetail = new JobDetailImpl("GrabJob", null, typeof(GrabJob));
var trigger = TriggerBuilder.Create()
    .WithIdentity("GrabJobTrigger")
    .WithSimpleSchedule(x => x
        .RepeatForever()
        .WithIntervalInMinutes(1)
    )
    .StartAt(DateTimeOffset.UtcNow.AddSeconds(30))
    .Build();
    scheduler.ScheduleJob(jobDetail, trigger);

这就是工作:

public class GrabJob : IJob {

    private readonly IGrabService _grabService;

    public GrabJob(IGrabService grabService) { _grabService = grabService; }

    public void Execute(IJobExecutionContext context) {
        _grabService.CrawlNextAsync("");
    }

}

GrabService实现是这样的:

public class GrabService : IGrabService {

    private readonly GrabberContext _context;

    public GrabService(GrabberContext context) {
        _context = context;
    }

    public async Task CrawlNextAsync(string group) {
        try {
            var feed = await _context.MyEntities.FindAsync(someId); // line #1
            // at the line above, I'm getting the mentioned error...
        } catch(Exception ex) {
            Trace.WriteLine(ex.Message);
        }
    }
}

但是当执行到line #1时,我收到了这个错误:

  

ObjectContext实例已被释放,无法再使用   对于需要连接的操作。

请问好吗?

1 个答案:

答案 0 :(得分:3)

您正在通过同步方法CrawlNextAsync()调用异步方法Execute()。只要CrawlNextAsync()点击... await _context ...,它就会返回,然后Execute()会返回,我会在此时假设GrabJob,因此{{ 1 {},因此GrabService被处置,而GrabberContext中的延续继续(并尝试使用被处置的CrawlNextAsync())。

作为一个简单的修复,您可以尝试更改

GrabberContext

public void Execute(IJobExecutionContext context) {
    _grabService.CrawlNextAsync("");
}