Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Return Void in Async Method in Web API

I am calling a method in Web API(C#) from repository. The method is repository is not returning anything. It is Void. whay should I return in my API method as a async method cannot have a Void return type.

This is my Async method in API:

    [HttpPost]
    [Route("AddApp")]
    public async Task<?> AddApp([FromBody]Application app)
    {        
        loansRepository.InsertApplication(app);
    }

and this is EntityFrame work Insert in repository(I can cot change this by the way)

     public void InsertApplication(Application app)
    {

        this.loansContext.Application.Add(app);
    }

Sorry I made changes to the question, I am not sure what should I have for ? in the Task

like image 572
Alma Avatar asked May 04 '16 23:05

Alma


People also ask

Why do async void methods return void?

Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler. However, some semantics of an async void method are subtly different than the semantics of an async Task or async Task<T> method. Async void methods have different error-handling semantics.

Why do async event handlers return void?

Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler. However, some semantics of an async void method are subtly different than the semantics of an async Task or async Task<T> method.

What is the difference between await async void and task async?

Async void methods have different composing semantics. Async methods returning Task or Task<T> can be easily composed using await, Task.WhenAny, Task.WhenAll and so on. Async methods returning void don’t provide an easy way to notify the calling code that they’ve completed.

What are the different return types for Async methods?

There are three possible return types for async methods: Task, Task<T> and void, but the natural return types for async methods are just Task and Task<T>.


1 Answers

If you do not want to return anything then the return type should be Task.

[HttpPost]
[Route("AddApp")]
public async Task AddApp([FromBody]Application app)
{
    // When you mark a method with "async" keyword then:
    // - you should use the "await" keyword as well; otherwise, compiler warning occurs
    // - the real return type will be:
    // -- "void" in case of "Task"
    // -- "T" in case of "Task<T>"
    await loansRepository.InsertApplication(app);
}

public Task InsertApplication(Application app)
{
    this.loansContext.Application.Add(app);

    // Without "async" keyword you should return a Task instance.
    // You can use this below if no Task is created inside this method.
    return Task.FromResult(0);
}
like image 183
Gabor Avatar answered Oct 21 '22 15:10

Gabor