0

What is actually returned by a Web API method with the following signature?

    [HttpPost]
    public async Task<IHttpActionResult> Post([FromBody] ReviewViewModel review)
    {
        using (var context = new BooksContext())
        {
            var book = await context.Books.FirstOrDefaultAsync(b => b.Id == review.BookId);
            if (book == null)
            {
                return NotFound();
            }

            var newReview = context.Reviews.Add(new Review
            {
                BookId = book.Id,
                Description = review.Description,
                Rating = review.Rating
            });

            await context.SaveChangesAsync();
            return Ok(new ReviewViewModel(newReview));
        }
    }

Method taken from: http://www.developerhandbook.com/c-sharp/create-restful-api-authentication-using-web-api-jwt/

I'm considering that it is either:

1) The framework does not return a response to the calling client until .IsCompleted is true, or 2) The framework does return to the client but the client must handle the situation gracefully, or 3) Something else entirely.

4
  • It is number 1) Commented Jan 30, 2017 at 20:48
  • Once you understand the state machine behind the async syntatic sugar it is somewhat easier to realize what is really happening. Commented Jan 30, 2017 at 20:49
  • 1
    I thought I understood the state machine, but this would be the Web API providing extra functionality on top of that, yes? Commented Jan 30, 2017 at 20:52
  • Possible duplicate of How does await async work in C# Commented Jan 30, 2017 at 20:53

2 Answers 2

5

async actions are an implementation detail.

The framework will wait for the Task to resolve; the client won't notice any difference.

Sign up to request clarification or add additional context in comments.

Comments

2

From the link you provided:

Writing asynchronous code in this manner allows the thread to be released whilst data (Books and Reviews) is being retrieved from the database and converted to objects to be consumed by our code. When the asynchronous operation is complete, the code picks up where it was up to and continues executing. (By which, we mean the hydrated data objects are passed to the underlying framework and converted to JSON/XML and returned to the client).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.