HttpClient - task was cancelled

本文探讨了使用C#的HttpClient时遇到的任务被取消错误。详细分析了默认超时设置为100秒的原因,以及在网络限制下如何影响大量请求的处理。文章还提到一些可能的解决方案,包括绕过限制的方法及确保应用适用于64位平台。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

refs:

https://stackoverflow.com/questions/19120675/httpclient-task-was-cancelled-how-to-get-the-exact-error-message

使用c#的httpClient时,发现运行一段时间后任务会cancelled报错,

查原因如下:


The default HttpClient.Timeout value is 100 seconds (00:01:40). If you do a timestamp in your catch block you will notice that tasks begin to get canceled at exactly that time. Apparently there is a limited number of HTTP requests you can do per second, others get queued. Queued requests get canceled on timeout. Out of all 600k of tasks I personally got only 2500 successful, others got canceled.

I also find it unlikely, that you will be able to run the whole 600000 of tasks. Many network drivers let through high number of requests only for a small time, and reduce that number to a very low value after some time. My network card allowed me to send only 921 requests within 36 seconds and dropped that speed to only one request per second. At that speed it will take a week to complete all the tasks.

If you are able to bypass that limitation, make sure you build the code for 64-bit platform as the app is very hungry for memory.


import requests import time import json import webbrowser API_URL = "https://ai.gitee.com/v1/async/audio/speech" API_TOKEN = "CL59BJQRJTUIENCWKWBPFTLOSTRS1YGZJIODXS18" headers = { "Authorization": f"Bearer {API_TOKEN}" } def query(payload): response = requests.post(API_URL, headers=headers, json=payload) return response.json() def poll_task(task_id): status_url = f"https://ai.gitee.com/v1/task/{task_id}" timeout = 30 * 60 retry_interval = 10 attempts = 0 max_attempts = int(timeout / retry_interval) while attempts < max_attempts: attempts += 1 print(f"Checking task status [{attempts}]...", end="") response = requests.get(status_url, headers=headers, timeout=10) result = response.json() if result.get("error"): print('error') raise ValueError(f"{result['error']}: {result.get('message', 'Unknown error')}") status = result.get("status", "unknown") print(status) if status == "success": if "output" in result and "file_url" in result["output"]: file_url = result["output"]["file_url"] duration = (result.get('completed_at', 0) - result.get('started_at', 0)) / 1000 print(f"🔗 Donwload link: {file_url}") print(f"⏱️ Task duration: {duration:.2f} seconds") # Open the result URL in the browser webbrowser.open(file_url) else: print("⚠️ No output URL found") elif status in ["failed", "cancelled"]: print(f"❌ Task {status}") else: time.sleep(retry_interval) continue task_file = f"task_{task_id}.json" with open(task_file, "w") as f: json.dump(result, f, indent=4) print(f"Task was saved to file {task_file}") return result print(f"⏰ Maximum attempts reached ({max_attempts})") return {"status": "timeout", "message": "maximum wait time exceeded"} if __name__ == "__main__": print("Creating task...") result = query({ "inputs": "Hello, world!", "model": "Spark-TTS-0.5B", "gender": "male", "pitch": 3, "speed": 3 }) task_id = result.get("task_id") if not task_id: raise ValueError("Task ID not found in the response") print(f"Task ID: {task_id}") task = poll_task(task_id) if task.get("status") == "success": # Do something with the task result here print("Task completed successfully!") 使用java代码重写上面这段代码
06-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值