编程语言
首页 > 编程语言> > c#-将异步方法作为Quartz.NET作业运行并处理对象问题

c#-将异步方法作为Quartz.NET作业运行并处理对象问题

作者:互联网

我在这种情况下使用Quartz.NET(需要提到GrabberContext是DbContext扩展类):

// 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);
        }
    }
}

但是,当执行到达第1行时,我会收到此错误:

The ObjectContext instance has been disposed and can no longer be used
for operations that require a connection.

有什么想法吗?

解决方法:

您正在从同步方法Execute()调用异步方法CrawlNextAsync().一旦CrawlNextAsync()击中…等待_context …,它就会返回,然后Execute()然后返回,我假设在那一刻GrabJob以及GrabService以及GrabberContext被处置了,而继续CrawlNextAsync()继续(并尝试使用已处置的GrabberContext).

作为一个简单的解决方法,您可以尝试更改

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

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

标签:quartz-net,async-await,quartz-net-2-0,c,entity-framework
来源: https://codeday.me/bug/20191118/2025499.html