Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple thread in EF 5

I have two thread in my application . one thread(actually it is a web api which can be called by another system.) new a Context to save entity (calling savechanges() method). Another thread (it is a real working thread .)new a Context to count entity(calling count() method). and these two thread are working on a same entity . As my application run , sometimes a exception will be thrown . here is it .please check it .

System.InvalidOperationException
Stack:
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type)
at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Count[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.IQueryable`1<System.__Canon>, System.Linq.Expressions.Expression`1<System.Func`2<System.__Canon,Boolean>>)
at Accela.HotDeploy.Website.Facade.DeployLogService.GetUpgradeProcess(System.Guid)

I believed it must be caused by some threading issue.Any ideas for this issue? thanks.

like image 248
malai.kuangren Avatar asked Mar 23 '26 04:03

malai.kuangren


1 Answers

EF is not thread-safe. You cannot use the same ObjectContext from multiple threads. You cannot even execute read-queries concurrently.

So you either need to synchronize (using locks) or use different ObjectContexts for different threads.

like image 168
usr Avatar answered Mar 25 '26 17:03

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!