I searched a lot about these subjects, but I'm still not sure it works as expected. And why.
What I understand:
- While processing a web request, you are using one of IIS thread from its pool. Within that request if you use an async call to, for example, query some data from a database, you free up that thread, so that IIS can use that same thread to process another call. That’s good. Probably.
- Sometime later when the database finally gives the awaited data, the code resumes. The async documentation mention that you now COULD be in another thread. Or not. DotNet's decision. If it's in the same thread as before, that’s ok.
- I use Dependency Injection to inject and close the context on a PerRequest lifetime (using Microsoft Unity). Closing is my main concern here. It works perfectly in my synchronous world: the dbcontext is closed at the end of my web request.
- EntityFramework is known to have its DbContext NOT thread safe
Question 1: Now if the resuming code is in another thread, is it from the same thread pool IIS has to process all requests or Is it from another side-pool?
Question 2: If the code runs in another thread, what about the WebRequest context? Will the DI track correctly the end of that deferred call and not call Dispose() before the async code is really over?
Question 3: If I use the async methods of EntityFramework, like ToListAsync or FirstOrDefaultAsync I read everywhere that "It should be ok". Can someone elaborate on that? Does EF track specifically the web request or the initial thread? Is there some sort of capture happening? Will my dbcontext be mixed up with another web request reusing my initial thread?
Question 4: If I use the normal (sync) methods of EntityFramework but wrapped within a Task. Whats gonna happen? Is it still "It should be ok"?
Sorry, that’s a lot of questions, its been bothering me for a long time now.