我使用HttpClient的GET请求循环陷入了aggregateexception的神秘混乱中

本文关键字:aggregateexception 混乱 循环 HttpClient GET 请求 | 更新日期: 2023-09-27 18:13:39

我不熟悉这种语言,不熟悉HttpClient,不熟悉多线程,所以请耐心听我说。我有一个Windows窗体应用程序,允许用户输入ID。当他们按下开始,它将开始重复地向某个网站的web API发出请求(直到他们按下停止),每次将ID增加1。ID包含在请求中;它使站点返回与该ID关联的虚拟对象的JSON表。每分钟有数千件这样的物品上传到网站。

下面是我用来发出请求的方法:

private async Task<string> GetResponseText(HttpClient client, string address)
{
        return await client.GetStringAsync(address);
}

所以在我处理程序开始扫描时发生的事情的代码部分,我首先创建一个新的HttpClient,像这样:

HttpClient client = new HttpClient();

然后我创建一个全新的线程并开始循环:

System.Threading.Thread scanThread = new System.Threading.Thread(() =>
{
    while (scanning)
    {
        string assetUrl = "https://api.example.com/blah?id=" + assetId.ToString();
        string response = GetResponseText(client, assetUrl).Result;
        dynamic assetJson = JsonConvert.DeserializeObject(response);
        if (assetJson != null)
        {
            this.Invoke((MethodInvoker)delegate
            {
                try
                {
                    // omitted lots of irrelevant stuff
                    assetId += 1;
                }
                catch (RuntimeBinderException)
                {
                    // this probably means the ID doesn't exist yet so I do nothing
                }
            });
        }
    }
    System.Threading.Thread.CurrentThread.Abort();
});
scanThread.IsBackground = true;
scanThread.Start();

我第一次运行时,它工作得很好。它对每个ID都成功了,每秒至少处理5到10个请求。没有奇怪的例外或幕后问题或类似的事情。但是,出乎意料的是,在大约一百个或两个请求之后,我遇到了第一个问题:

A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll
A first chance exception of type 'System.AggregateException' occurred in mscorlib.dll
An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
Additional information: One or more errors occurred.

堆栈跟踪将问题缩小到这一行:

string response = GetResponseText(client, assetUrl).Result;
"没关系,"我对自己说。我不知道哪里出了问题,所以我为那条线设置了一个try/catch块。这是真正让我挠头的部分。 有了try/catch,一旦出现这个错误,它就会在整个循环中不断地发生。它永远不会恢复或正常继续。有两种方法可以修复它,第二种方法是最奇怪的:

1)直接关闭程序并重新打开

2)停止扫描,耐心等待6行左右出现在Visual Studio的调试输出中关于线程退出的信息,然后重新开始扫描

我觉得第二种情况是关于为什么会发生这种情况的线索,但我不够好,无法弄清楚。发生什么事情了?为什么等待一些线程关闭(不管它们开始是什么)可以解决这个问题?我能在每次循环运行时手动删除它们吗?

我使用HttpClient的GET请求循环陷入了aggregateexception的神秘混乱中

HTTP-Statuscode 400表示您的请求无效。因此,您必须详细检查HTTP-Request。也许API只允许有限数量的访问或其他。

进一步,我会给你一些更现代的代码示例:

   var ts = new CancellationTokenSource();
   CancellationToken ct = ts.Token;
    private void Start()
    {
       var task = Task.Factory.StartNew(() => {
         var client = new HttpClient();
         while(true)
         {
            if (ct.IsCancellationRequested)
            {
               break;
            }
            string assetUrl = "https://api.example.com/blah?id=" + assetId;
            string response = await GetResponseText(client, assetUrl);
            dynamic assetJson = JsonConvert.DeserializeObject(response);
            if (assetJson != null)
            {
               assetId++;
            }
         }
       }, ct).ContinueWith(ex => Console.WriteLine(ex.Message), TaskContinuationOptions.OnlyOnFaulted);
     }

     private void Stop()
     {
        ct.Cancel();
     }
相关文章:
  • 没有找到相关文章