0

I'm using Linq to Entities to perform database operations .

Problem is if data is not there in cache object I tried to take it from database using single thread.

it gives me following error :

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

to overcome I tried the following solution:

using (var tran = new TransactionScope())
{
    Task.Factory.StartNew(() => DoSomething());
    Task.Factory.StartNew(() => DoSomethingElse());
    // Wait all
    tran.Complete();
}

but instead if this can I do it using another thread running:

//My code
//thread to run Method1() 
method 1()
{
//DO SOMETHING
//CALL METHOD2()
} 

Is it good to simply do like:

string res = null;
Thread newThread = new Thread(() => {res = Method2();});
4
  • 3
    Both the context and the transactionscope are not thread safe AFAIK, so reuse of either in multiple threads or tasks or in an async way is not going to work. Commented Mar 10, 2015 at 6:03
  • :( what should I do in my scenario ? can you help me Commented Mar 10, 2015 at 6:06
  • @AkashKava Where do you see him using "async features?" He's only executing two delegates on a threadpool thread. He's executing them in parallel, but they aren't async. Commented Mar 10, 2015 at 7:33
  • @YuvalItzchakov question title indicates async so I assumed he is further using async operations inside those threads. Sorry for that. I removed my comment. Commented Mar 10, 2015 at 7:36

1 Answer 1

2

The error message indicates the problem very accurately. The database context is not thread safe. Therefore you cannot access the database context from a different thread from that which created it.

Your question clearly indicates you do not understand threading at all and so you really need to begin by researching how threads work and what it means to be thread safe.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.