1

I have a case where I want to put EF inserts inside Task and return results without making user to wait like this:

Task.Factory.StartNew(() =>
{
   InsertToDatabase(data);
});

But for this I must create new DbContext because other one will be disposed of course so I need to initialize repositories again. I am using constructor injection but in this case I can't resolve this dependency. How I should create my repositories inside Task.Factory?

user2412672
  • 1,459
  • 3
  • 20
  • 36
  • 1
    Just create a new context and use `await` with async versions of EF rather than calling `Task.Factory.StartNew()`. The latter is a poor use of async mechanisms for your example. –  Mar 12 '16 at 15:12
  • but await will wait until inserts will be completed. I have long executing code and also inserts so I want then to run in background. I don't want to create new Context because I don't that service had reference to data project it has reference to data.contracts project – user2412672 Mar 12 '16 at 16:10
  • So. If you are going to use `Task` then you need to wait (`await`; or `Task.WaitAll()`) otherwise you run the risk of the main app exiting before the task completes. [EF contexts are not thread-safe](http://stackoverflow.com/questions/4455634/entity-framework-thead-safety) –  Mar 13 '16 at 00:26
  • @MickyD, there is `Task.WaitAll` for that – Toolkit Jan 22 '17 at 14:57
  • @Toolkit for what? I already said that anyway –  Jan 22 '17 at 16:24

0 Answers0