czifro
czifro

Reputation: 784

What behavior should be expected for async methods?

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:

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

Answers (1)

Dan
Dan

Reputation: 10538

In order:

  • Does the async call prevent the calling method from returning until the async finishes due to await?

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 awaited Task has completed (or throws an exception).

  • Would it be safe to change the return type from Task to void?

Yes - but you're unable to await void async methods. This is generally OK for event listeners but I wouldn't recommend it elsewhere.

  • What happens to an async call when the calling thread is terminated (in the instance the request sends response back to client and closes thread)?

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

Related Questions