jav*_*iry 3 c# entity-framework quartz.net async-await quartz.net-2.0
我在这个上下文中使用 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);
Run Code Online (Sandbox Code Playgroud)
这就是工作:
public class GrabJob : IJob {
private readonly IGrabService _grabService;
public GrabJob(IGrabService grabService) { _grabService = grabService; }
public void Execute(IJobExecutionContext context) {
_grabService.CrawlNextAsync("");
}
}
Run Code Online (Sandbox Code Playgroud)
该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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是当执行到达时,line #1我收到此错误:
ObjectContext 实例已被释放,不能再用于需要连接的操作。
请问有什么想法吗?
您正在CrawlNextAsync()从同步方法调用异步方法Execute()。一旦CrawlNextAsync()命中...... await _context,它就会返回,Execute()然后返回,我假设在那个时候GrabJob,因此GrabService,因此GrabberContext,被处置,而继续CrawlNextAsync()继续(并尝试使用处置GrabberContext)。
作为一个简单的修复,您可以尝试更改
public void Execute(IJobExecutionContext context) {
_grabService.CrawlNextAsync("");
}
Run Code Online (Sandbox Code Playgroud)
到
public void Execute(IJobExecutionContext context) {
_grabService.CrawlNextAsync("").Wait();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2894 次 |
| 最近记录: |