Blog Home  Home Feed your aggregator (RSS 2.0)  
Mayur's Blog - My Favourite C# 7.0 Feature: Generalized Async Return Type - ValueTask
 
# Thursday, April 13, 2017

Consider the following code snippet where a new student entity is being added to the database using Asp.Net MVC API.

Here the entity is being validated first before added. Whenever the entity fails the validation, a relevant message is returned without calling any database operation.

There is no need to trigger any ASYNC operation if there is no database operation is involved. However, the following API returns Task<T>. Therefore, the run time is going to take some trouble to invoke required resources to generate the task. That's how async-await programming worked so far in most cases.

public async Task<IHttpActionResult> Post(Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    return BadRequest($"Input is not valid. Error message: {ModelState.Values.First().Errors.First().ErrorMessage}");
                }
                else
                {
                    entityContext.Students.Add(student);

                    await entityContext.SaveAsync();      
                }
                
                return Ok();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return ApiExceptionMessage(ex.Message, ex);
            }
        }

C# 7.0 provides an easier way to resolve this issue.  Generalized Async type: ValueTask<T>

Instead of returning Task<T> we could have returned ValueTask<T>. If ValueTask<T> was used, then the runtime would not have taken any trouble to set up the extra resources. That would have made processing faster.

There is a pre-requisite for this. Before using ValueTask<T>, please make sure that you download the following NuGet package.

System.Threading.Tasks.Extensions

Thursday, April 13, 2017 7:18:16 PM UTC  #       | 
Copyright © 2020 Mayur Bharodia. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: