There's a lot of problems here, actually. Your core problem is likely inside the SendRegisterConfirmationAsync
method. However, you haven't provided the code for that method. If I had to guess, you're using using
statements in a not thread-safe way, based on the error message.
However, it's also entirely possible this is just due to handling async improperly. You're calling an async method from a sync method. Since SendEmail
returns void, you're either swallowing the return value of the async method or the async method is async void
(which you should pretty much never do). In either case, since you're not awaiting the result of the async method, the rest of your code is moving on potentially taking dependencies with it. For example, things like your DbContext
are request-scoped, so if that async method utilizes your DbContext
, but doesn't finish before the response is sent, the context will be disposed right from under it, causing exceptions. If you use async, you need to go async all the way.
Further, there's really no such thing as a true "background" task in a web application context. Task.Run
merely pulls another thread from the same pool your requests are being handled from. You may allow one thread to return, but you're still sitting on another, so the best case scenario is that you've bought yourself nothing. The worst case scenario is that you've now effectively halved your server's throughput and killed your ability to scale.
If you want to do something in the background, offload it to a background process, i.e. outside the context of your web application. You can use something like Hangfire or Revalee.