public class EventService
{
public async Task InsertEventItemAsync(InsertEventItem request)
{
await SomeMethodThatUsesRestSharpToMakeAsynchronousWebApiCall(request);
}
public async Task<int> GetNumberOfEvents()
{
int result = await SomeOtherMethodThatUsesRestSharpToMakeAsynchronousWebApiCall();
return result;
}
}
public interface IFoo
{
void Bar();
int Baz();
}
public class Foo : IFoo
{
EventService _eventService;
public void Bar()
{
Task.Run(async () => await _eventService.InsertEventItemAsync());
}
public int Baz()
{
int result = Task.Run(async () => await this._eventService.GetNumberOfEvents()).Result;
return result;
}
}
That call to Task.Run in Foo.Bar() does not look right to me. It is the approach to async code that is used everywhere in the codebase for a project I have recently started on. My assumption is that that async lambda was written just so that the code will compile. I am doubtful that it a good approach.
I don't have much experience with async/await but I think that this will start a new ThreadPool thread and block the current thread until the task has finished runninng on the ThreadPool thread, which will result is worse performance than if the whole lot was synchronous.
Is that code "wrong"?
It seems to me like there might be an aversion (or possibly a good reason) to going async all the way. Should I try to make the case for going either fully async or fully sync and not trying to mix them?
Thanks.
Foo.Barwill start a new task that executes on the task pool. No new thread is created.Foo.Barreturns immediately while the task executes asynchronously ("fire and forget"). Is the code wrong? It depends on what you want to achieve. You can replace the async delegate with a "normal" delegate for a slight optimization in the generated IL.Resultproperty of a task will block until the task completes so it no longer is "fire and forget". The likelihood of deadlocks in your code should be zero. If it is not you need to fix the root cause of the deadlocks. However, when your code involves callbacks into code that is not reentrant you can sometimes avoid deadlocks by scheduling these callbacks on new tasks/threads. Your questions seem to be about a general understanding of async and await and I suggest that you study this topic and/or write some simple code to gain a better overall understanding.