1

I have SQL Server Express 2013 and I am using EF6 that has async methods to interact with the database. I am using a code like this:

Task<List<MyType>> tskResult = Repository.getMyTypeAll();
Task.WaitAll(tskResult);

Where getMyTypeAll return all the records from a table. The problem is that in the second line, the code is awating all the time, is blocked. It seems that the repository does not get response from the database with the result.

So I am wokdering if I need to configure some parameter in my database to allow the async comumunication or is something that I would have by default.

svick
  • 236,525
  • 50
  • 385
  • 514
Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    I think you should just await it. Or await Task.WhenAll if there are actually multiple tasks. – Casey Oct 21 '14 at 16:42
  • Well, this is in my constructor, and I can't use async keyword in the method and then I can't use await with my method in the repository. – Álvaro García Oct 21 '14 at 16:50
  • 1
    Don't use the async EF methods in your constructor. In fact, it's probably a bad idea to call the database in your constructor too. – Casey Oct 21 '14 at 16:55
  • Thanks for the tip, but I would like to know why the application is freeze when I use the async methods, because it's seems that the repository is not able to get the response from the database because the connection is lost. – Álvaro García Oct 21 '14 at 17:00
  • 1
    I suspect your problem has to do with calling async methods from sychronous code rather than something with the database, though; [this](http://stackoverflow.com/q/9343594/2441808) might be helpful. – Casey Oct 21 '14 at 17:04
  • I try in another method taht is not a constructor to use the async/await keywords. In this case the aplication is not blocked, so I don't need to configure SQL Server. – Álvaro García Oct 21 '14 at 17:35
  • If you answer the question I will accept you as answered. Thanks. – Álvaro García Oct 21 '14 at 17:36
  • OK, I tried to sum up the important points in one cohesive answer. – Casey Oct 21 '14 at 18:20

1 Answers1

1

Your problem isn't because of your SQL Server configuration; rather, you're running into blocking issues calling async methods from synchronous code. See this question for information about how you can do this.

However, as a general rule, you don't want to call async code from synchronous methods because it's difficult and prone to these sorts of issues. Normally I'd recommend making your method async and just using await, but you've indicated that this code is in your constructor, so that's not a possibility. If you absolutely need to call EF methods from your constructor, use the synchronous ones (I believe many of the async ones may be implemented with Task.FromResult anyway), but as a general rule you don't want your constructor to be making database calls. Object instantiation should be cheap.

Community
  • 1
  • 1
Casey
  • 3,307
  • 1
  • 26
  • 41