Reputation: 5962
I have some long time taking process(to Get data from Db like Country List, Business List (around 1500 rows)). So I created a separate method to get those data.
But It is saying
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.
private IList<Business> GetBusiness(IRepositories repos, IImageStore store)
{
var data = repos.BusinessRepo.GetAll();
//Some more calculation on the basis of Data.
return data;
}
**similar function for country**
Now I'm calling those method from main
Task<List<Business>>[] taskBusiness = new Task<List<Business>>[1];
taskBusiness[0] = Task.Run(() => GetBusiness(repos, imageStore));
Task<List<Country>>[] taskCountry = new Task<List<Country>>[1];
taskCountry[0] = Task.Run(() => GetCountry(repos, imageStore));
//Some More calculation
.
.
// before method end
Task.WaitAll(taskBusiness);
Task.WaitAll(taskCountry);
var business = taskBusiness[0].Result;
var country = taskCountry[0].Result;
Upvotes: 0
Views: 495
Reputation: 118947
The DbContext
class is not thread safe (your error message pretty much tells you that) so you should never use the same instance in multiple threads. Instead, you should create a different object for every simultaneous call.
From the MSDN documentation on DbContext
(emphasis mine):
Thread Safety: Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Upvotes: 1