Using async/await and returning Task

2019-03-15 18:37发布

I have a Portable Class Library (PCL) method like this:

public async Task<string> GetLineStatuses()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    {
        return response.GetResponseStream().ReadAllText();
    }
}

My ASP.NET Web Api method looks like this:

public async Task<HttpResponseMessage> Get()
{
    HttpResponseMessage response = new HttpResponseMessage();
    string statuses = await service.GetStatuses();
    response.Content = new StringContent(statuses);
    return response;
}

What are the implications of returning a Task in Web API. Is this allowed? The only reason I want to use await is so I can use a Portable Class Library (PCL). What is the best practice? Should I have a syncronous version of my method and an asyncronous version? What are the performance and code readability and maintainability implications?

Also would I have the same effect if I returned Task<string> rather than Task<HttpResponseMessage>?

1条回答
等我变得足够好
2楼-- · 2019-03-15 19:35

Async and await are perfectly acceptable in ASP.NET. Here's a Scott Handselman video demoing it: http://www.asp.net/vnext/overview/aspnet/async-and-await

"Also would I have the same effect if I returned Task<string> rather than Task<HttpResponseMessage>?"

Not really sure what you mean by this. The Task is like a container for the object, so a Task<string> would contain your string result and a Task<HttpResponseMessage> would contain your HttpResponseMessage result... Is that what you mean? I think either method is perfectly acceptable. If you just need the string, then go with that. No point in returning more than you need.

查看更多
登录 后发表回答