简体   繁体   中英

Stuck with Async Task and Await

I don't know whats wrong with this code, but still it doesn't respond the needed value.

Here is my sample code:

WebAPI 2:

KOTController.cs

[HttpGet]
[Route("testasync")]
public IHttpActionResult TestAsync()
{
    try
    {
        return Ok(_iKOTManager.TestAsync());
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        return null;
    }
}

Interface

IKOTManager.cs

Task<int> TestAsync();

KOTManager.cs

public async Task<int> TestAsync()
{
    return await Task.Run<int>(() =>
    {
        return 999 + 23;
    });
}

When I send a request to this API, it returns something like this not the number

<TaskOfint xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System.Threading.Tasks"/>

Any advice would be really helpful. Thank you.

You get that response because you are return the Task and not actually executing it. The framework is just serializing the task object and returning that.

Refactor the action to return Task and then await the method on interface

[HttpGet]
[Route("testasync")]
public async Task<IHttpActionResult> TestAsync() {
    try {
        return Ok(await _iKOTManager.TestAsync());
    } catch (Exception ex) {
        logger.Error(ex);
        return InternalServerError();
    }
}

Reference: Async/Await - Best Practices in Asynchronous Programming

Additionally, in the case of the exception you should return an appropriate result instead of null . This should eventually be refactored out as handling errors within the controller is considered a cross-cutting concern . Controllers should as lean as possible.

[HttpGet]
[Route("testasync")]
public async Task<IHttpActionResult> TestAsync() {
    return Ok(await _iKOTManager.TestAsync());
}

You need to change your controller to be async and then await the task. ie

public async Task<IHttpActionResult> TestAsync()

...

return Ok(await _iKOTManager.TestAsync());

See the documentation for async / await here .

Your action method is consuming/calling async method, you need to make your action method as well async to return Task<T> as return type like:

[HttpGet]
[Route("testasync")]
public async Task<IHttpActionResult> TestAsync()
{
    try
    {
        return Ok( await _iKOTManager.TestAsync());
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        return null;
    }
}

If we are calling an async method, if possible we should make the calling side method as well async and return Task<T> in all call chains.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM