I recently came across this code written by a contractor we had working for us. It's either devilishly clever or silly (I think the latter but I wanted a second opinion). I'm not massively up to speed on async
await
.
Basically it worked like this:
public bool Send(TemplatedMessageDto message)
{
return Task.Run(() => SendAsync(message))
.GetAwaiter()
.GetResult();
}
public async Task<bool> SendAsync(TemplatedMessageDto message)
{
//code doing stuff
var results = await _externalresource.DothingsExternally();
//code doing stuff
}
Now as I understand it that first Task.Run()
is pointless and inefficient? and should really be:
public bool Send(TemplatedMessageDto message)
{
return SendAsync(message))
.GetAwaiter()
.GetResult();
}
public async Task<bool> SendAsync(TemplatedMessageDto message)
{
//code doing stuff
var results = await _externalresource.DothingsExternally();
//code doing stuff
}
I'm also not convinced this is really an async method because it will still wait, right? I think it's only advantage (even re-written) is to free up the main worker thread.
Can someone confirm that this first Task shouldn't be there?
GetAwaiter().GetResult()
call instead of.Result
? And why wait at all instead of writingpublic async Task<bool> Send ... await Task.Run();
? – FaustaTask.Run
isn't inefficient -async
doesn't make anything run asynchronously. Everything up toawait
will run on the calling thread. If you need it to run concurrently, you should useTask.Run
, or better yet, extract it to its own method that will be called with Task.Run – Fausta