dotnetcore / CAP

Distributed transaction solution in micro-service base on eventually consistency, also an eventbus with Outbox pattern
http://cap.dotnetcore.xyz
MIT License
6.68k stars 1.28k forks source link

Cannot access a disposed context instance #1502

Closed frank-wxs closed 7 months ago

frank-wxs commented 7 months ago

`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.

frank-wxs commented 7 months ago

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

yang-xiaodong commented 7 months ago

Is this issue similar to #1368 ?

frank-wxs commented 7 months ago

Is this issue similar to #1368 ?

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

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

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

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

frank-wxs commented 7 months ago

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