当我使用ReadAsStringAsync()时,如何避免将我的方法设置为异步?

时间:2016-01-29 07:38:57

标签: c# asp.net asynchronous task

我正在使用C#和.NET Framework 4.0开发一个库。

我有这种方法在ASP.NET Web Api 2 Web服务上输入一些东西。

public async Task<string> PrepareAndStartv2(
    string orderNumber,
    string userName,
    string systemName)
{
    string uri =
        string.Format(PrepareAndStartUri, orderNumber, userName, systemName);

    string batchName = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(webApiHost);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpContent content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

        Task<HttpResponseMessage> response = client.PutAsync(uri, content);
        HttpResponseMessage message = response.Result;

        Task<string> task = message.Content.ReadAsStringAsync();

        batchName = await task;
    }

    return batchName;
}

我添加了message.Content.ReadAsStringAsync()来获取方法返回的字符串。在那之后,我被迫和Task<string>awaitasync无处不在。

是否还有其他选项可以在HttpContent中使用awaitTask<string>async读取字符串?

也许在这个PrepareAndStartv2方法中运行一个等待我将正在使用ReadAsStringAsync()读取字符串的任务。

1 个答案:

答案 0 :(得分:2)

调用异步方法后可以使用Task.Result以避免强制异步执行自己的方法:

public string PrepareAndStartv2(
    string orderNumber,
    string userName,
    string systemName)
{
    string uri =
        string.Format(PrepareAndStartUri, orderNumber, userName, systemName);

    string batchName = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(webApiHost);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpContent content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

        HttpResponseMessage message = client.PutAsync(uri, content).Result;
        batchName = message.Content.ReadAsStringAsync().Result;
    }

    return batchName;
}