使用C#

时间:2016-12-07 17:16:31

标签: c# async-await

我有以下代码:

 //ids are a list of strings
foreach (string id in ids)
{
    string serviceurl = "https://xxx.xx.xxx/internal/v2/idsearch?id=" + id;
    List<string> lst = new List<string>();
    var task =  WebUtil.MakeAsyncRequest("GET", serviceurl, "application/json");
    string val =  task.Result;
    if (val != "")
      lst.Add(val);
}

public static Task<string> MakeAsyncRequest(string method,string url, string contentType)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.ContentType = contentType;
    request.Method = method;
    request.Timeout = 20000;
    request.Proxy = null;

    string clientId = ConfigManager.GetClientId;
    string clientSecret = ConfigManager.GetClientSecret;
    request.Headers.Add(HttpRequestHeader.Authorization, ConfigManager.GetServiceKey);
    request.Headers.Add("client_id", clientId);
    request.Headers.Add("client_secret", clientSecret);

    Task<WebResponse> task = Task.Factory.FromAsync(
        request.BeginGetResponse,
        asyncResult => request.EndGetResponse(asyncResult),
        (object)null);

    return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}

private static string ReadStreamFromResponse(WebResponse response)
{
    using (Stream responseStream = response.GetResponseStream())
    using (StreamReader sr = new StreamReader(responseStream))
    {
        //Need to return this response 
        string strContent = sr.ReadToEnd();
        return strContent;
    }
}

一切正常但我不确定我是否正确实施async进程,因为它似乎正在同步执行。我真的很感激能帮我辨别我做错的人...谢谢!

编辑:

以下是我如何解决它......

var taskList = new List<Task<string>>();
foreach (string id in ids)
{
    string serviceurl = "https://xxx.xx.xxx/internal/v2/idsearch?id=" + id;
    taskList.Add(WebUtil.MakeAsyncRequest(serviceurl, "application/json"));      
}
try
{
  string[] val = await Task.WhenAll(taskList.ToArray());
}
catch (Exception)
{                
  throw;
}

public static async Task<string> MakeAsyncRequest(string url, string contentType)
    {

        using (HttpClient client = new HttpClient())
        {
            var requestMessage = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };

            // Add our custom headers
            requestMessage.Headers.Add("client_id", ConfigManager.GetClientId);
            requestMessage.Headers.Add("client_secret", ConfigManager.GetClientSecret);
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue(ConfigManager.GetServiceKey);
            requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));


            HttpResponseMessage response = await client.SendAsync(requestMessage);


            var result = await response.Content.ReadAsStringAsync();
            string res = result.ToString();

            return res;
        } 

    }

2 个答案:

答案 0 :(得分:3)

ReadToEnd是同步的,是的。有异步等价物。

另请注意,此处DNS解析是同步的。这是一个持续不被修复的错误。

可能最好的解决方法是使用HttpClient,这样可以异步下载字符串。

答案 1 :(得分:0)

我认为发出async请求的最佳方式是HttpClient。 你可以这样写:

var client = new HttpClient();
var request = new HttpRequestMessage() 
{
    RequestUri = new Uri("xxxxxx"),
    Method = HttpMethod.Get,
};

request.Headers.Accept.Add(new ....);
var response = await client.SendAsync(request);
//read a result from the repsonse