HttpClient异步-太快跳过Web服务请求

时间:2018-10-29 16:39:04

标签: c# api asynchronous httpclient

我遇到一个问题,即我遍历了约31个Web服务URL。 如果在顶部代码中放置Thread.Sleep(1000),它将很好地工作,但是如果删除此代码,则仅在31个请求中有10个(有时更少,有时更多)请求成功。如何等待它?

代码

foreach(var item in ss)
{ 
   //Call metaDataApi(url,conn,name,alias)
}

 public static void metadataApi(string _url, string _connstring, string _spname, string _alias)
        {
           // Thread.Sleep(1000);
            //Metadata creation - Table Creation
            using (var httpClient = new HttpClient())
            {
                string url = _url;

                using (HttpResponseMessage response = httpClient.GetAsync(url).GetAwaiter().GetResult())
                using (HttpContent content = response.Content)
                {
                    Console.WriteLine("CHECKING");
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("IS OK");
                        string json = content.ReadAsStringAsync().GetAwaiter().GetResult();

                       //Doing some stuff not relevant

                     }
                }
            }
         }

外观如何 enter image description here

1 个答案:

答案 0 :(得分:0)

您应该在可能的地方使用async/await,但是您可以尝试这样的操作:

// you should share this for connection pooling  
public static HttpClient = new HttpClient();

public static void Main(string[] args)
{
    // build a list of tasks to wait on, then wait
    var tasks = ss.Select(x => metadataApi(url, conn, name, alias)).ToArray();
    Task.WaitAll(tasks);
}

public static async Task metadataApi(string _url, string _connstring, string _spname, string _alias)
{
    string url = _url;
    var response = await httpClient.GetAsync(url);
    Console.WriteLine("CHECKING");
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("IS OK");
        string json = await content.ReadAsStringAsync();

        //Doing some stuff not relevant

    }
}

值得注意的是,这将尝试并行运行多个。如果您需要一个接一个地运行它们,则可能需要创建另一个async函数,该函数分别等待每个结果,然后从Main进行调用。 .Result有点反模式(使用现代c#语法,您可以在主函数上使用async),但对于您的脚本,它应该是“ ok”,但我会尽量减少使用(因此为什么我不在循环内使用.Result