c# - 使用 C# 的异步 HttpWebRequest 调用

标签 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;
        } 

    }

最佳答案

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

另请注意,此处的 DNS 解析是同步的。这是一个一直没有修复的错误。

也许,最好的解决办法是使用 HttpClient,这使得异步下载字符串变得简单。

关于c# - 使用 C# 的异步 HttpWebRequest 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41023502/

相关文章:

c# - 可以增强十字光标吗?

c# - 如何从另一个线程通知等待任务完成?

rust - 如何同步返回在异步 Future 中计算的值?

c# - 如何读取 C# 测试项目中的 app.config 值

javascript - 如果异步函数出错,如何执行代码块

javascript - 如何从 firestore 两个集合中获取数据并将所有数据合并在一起

c# - 在直接从调用另一个库返回任务的库中使用 ConfigureAwait(false) 是否有利?

c# - 使用 LINQ 从两个列表中获取所有可能的连接对

c# - 如何从现有的 Windows 服务启动 AspNetCore 应用程序

c# - 如何邀请Facebook申请?