Reputation: 784
Please forgive me if there is already a stack q that covers this, I could not find it.
I am working on a web api in asp.net that incorporates a lot of async tasks. I understand the behavior for most of them except for a particular endpoint. Here is an example of what I'm dealing with:
public class Service {
public async Task ReadMessageAsync()
{
var messages = db.Messages.Where(/*some pred*/);
foreach (var m in messages)
{
m.isNew = false
}
db.SaveChanges();
return Task.FromResult(0);
}
}
// in api controller
public async Task<IHttpActionResult> GetMessages(bool onlyNew)
{
var messages = service.GetMessages(onlyNew); // this is defined in service class
await service.ReadMessageAsync(); // async call to mark new messages as not new
return Ok(messages);
}
Some my question relates to the async call under a few different scenarios:
Task
to void
?I am pretty familiar with other behaviors for different use cases, but these are unclear. Any light that can be shed on this would be much appreciated. Thanks!
Upvotes: 1
Views: 87
Reputation: 10538
In order:
The async call will not prevent the callee from returning. If you use await
in the callee, then the callee will yield control back to the scheduler and the remainder of the method will be signed up as a continuation which will run once the await
ed Task
has completed (or throws an exception).
Yes - but you're unable to await
void
async methods. This is generally OK for event listeners but I wouldn't recommend it elsewhere.
No clue. Hopefully someone else can answer that. Given that await/async
signs up the rest of the method as a continuation one would assume that if the thread that invoked the Task is aborted, the continuation would be too. But I am talking out of my arse here.
Upvotes: 4