作为石英运行异步方法.NET作业和已处置对象问题

本文关键字:对象 问题 作业 石英 运行 异步方法 NET | 更新日期: 2023-09-27 18:12:10

我用的是石英。. 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实例已被处理,不能再使用对于需要连接的操作。

有什么想法吗?

作为石英运行异步方法.NET作业和已处置对象问题

您正在从同步方法Execute()调用异步方法CrawlNextAsync()。一旦CrawlNextAsync()登陆…await _context……,它返回,然后Execute()返回,我假设此时GrabJob,因此GrabService,因此GrabberContext,被删除,而CrawlNextAsync()中的延续继续(并试图使用被删除的GrabberContext)。

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

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

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