.net core中多线程中的上下文

发布时间:2020-07-06 17:12:34来源:本站阅读(904)

    开发中我们以常会用到多线程进行操作。

    在.net core中 Task里用到上下文时经常会遇到错误

    Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

    啥意思呢?如下

    无法访问已处置的对象。导致此错误的常见原因是,处理从依赖项注入中解决的上下文,然后在以后尝试在应用程序中的其他位置使用相同的上下文实例。如果在上下文上调用Dispose()或将上下文包装在using语句中,则可能会发生这种情况。如果使用依赖项注入,则应让依赖项注入容器负责处理上下文实例。 

    以上内容来源于翻译软件。

    很显然,我们是可以理解到的,上下文是依赖注入进来的, 生命周期也是注入时就定了的。我注入的是ServiceLifetime.Scoped,就是一个请求一个实例。当我们开Task时已经切换了线程,刚才的上下文已经释放了,不能再使用了。就报错了。

    这时怎么办呢。我们new一个出来。但真正写代码的时候就不容易了。framework的时候还好点。百度到都是在dbcontext里重写了配置,上下文不注入了。后来还是解决了。


     以上是代码。

    后来我又想到,如果我把注入和生命周期改下,是不是可以呢,这个需要测试下。完后补充。

关键字ef .net core