Context:
We've got a big inheritance tree with interfaces and the whole shabang. We feed a request to a factory, which creates the proper object, then we call a DoStuff() method that all of these objects expose. The method doesn't return anything, just sets some properties.
Problem:
In just a single case, inside the DoStuff() method, we have to call an async method, there's just no way around it because we don't have control over that method. Refactoring the entire inheritance tree to turn the DoStuff() method to use an async Task signature is not something we look forward to.
We're fine with blocking the thread until the operation finishes.
Question:
We've tried using RunSynchronously() on the method but we've got the following error:
System.InvalidOperationException: RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Threading.Tasks.Task.InternalRunSynchronously(TaskScheduler scheduler, Boolean waitForCompletion)
Should we use Wait() instead?
It depends if you are happy with the downsides. This is a web application, so you want to keep your threads as free as possible, however by using .Wait()
you have one additional thread unavailable on top of whatever threads are needed inside the async method for the continuations (or thread bound tasks, again not typical for a web app).
You won't see any deadlocks however, if this was what you were afraid of. ASP.NET Core doesn't use a non-default SynchronizationContext
, so you won't lock up, but be warned, it's a slippery slope to not being able to cope under load, as this is worse than the synchronous version.
If this were regular ASP.NET you would see deadlocks if any of the await
s inside of the async
method aren't using ConfigureAwait(false)
(it's not quite as black and white as that, but that's near enough the truth).