dotnetcore/CAP

Cannot access a disposed context instance

frank-wxs opened this issue · 4 comments

`public class SubscriberService : ICapSubscribe
{
private readonly HatDbContext dbContext;

public SubscriberService(HatDbContext dbContext)
{
    this.dbContext = dbContext;
}

[CapSubscribe("JobResultMerge")]
public async void JobResultMerge(long jobId)
{
    var job = await dbContext.Job.SingleAsync(m => m.Id == jobId);
    job.BatchNumber = "123";
    await dbContext.SaveChangesAsync();

    //await new HttpClient().GetAsync("http://localhost:55555/upload/temp/240322123121019/合并结果 (12).xlsx");

    job.BatchNumber = "321";
    await dbContext.SaveChangesAsync();


}

}`

When HttpClient.GetAsync is blocked, the program operates normally, and the BatchNumber is successfully modified to "321". However, if I use any await in the middle, an error will be reported the next time the database is saved. Cannot access a disposed context instance.

I am using the net core program. This is my configuration information for cap.

services.AddScoped<SubscriberService>();

services.AddCap(x => { x.UseInMemoryStorage(); x.UseInMemoryMessageQueue(); x.UseDashboard(); });

Is this issue similar to #1368 ?

Is this issue similar to #1368 ?

其实我是在CapSubscribe里面注入了我项目的其他Service,然后调用其他Service的异步方法的时候发现无法正常使用dbContext。

HttpClient().GetAsync只是我的举例,我上面注释的这段代码运行是正常的,只是放开后下面的dbContext.SaveChangesAsync就会报错。

问题的关键就是我用await执行异步方法之后,我的dbContext就会被disposed掉,不太理解为什么会这样。

并且我刚刚发现,异步方法如果不用await,直接使用.Result获取结果,我的dbContext就不会被disposed

Is this issue similar to #1368 ?
不用关注了,我找到原因了,我写了一个 public async void 方法····,把void 改为task就不会出现这个问题了