[英]Run HttpClient GetAsync in different threads
I have a scenario where I have x amount of queries and I want to run each query in a different thread.我有一个场景,我有 x 个查询,我想在不同的线程中运行每个查询。
My problem is the Http GetAsync method only works when it returns a Task, I tried to return a void but it did not work.我的问题是 Http GetAsync 方法仅在返回 Task 时才有效,我尝试返回 void 但它不起作用。 But to create multiple threads I need to return a void.
但是要创建多个线程,我需要返回一个空值。
public static async Task threadAsync(string query)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
try
{
watch.Restart();
HttpResponseMessage response = await client.GetAsync(query);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
watch.Stop();
string logData += $"Execution Time: {watch.ElapsedMilliseconds} ms, ";
watch.Reset();
var data = JObject.Parse(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
I have multiple methods in Threads class with different queries.我在 Threads 类中有多个具有不同查询的方法。 I tried using GetAwaiter().GetResult(), but that also did not work.
我尝试使用 GetAwaiter().GetResult(),但这也不起作用。 How can I use run each query in a different thread?
如何在不同的线程中运行每个查询?
public class Threads
{
public static void thread1Create()
{
string query = "SOMEQUERY";
threadAsync(query).GetAwaiter().GetResult()
}
};
want to run each query in a different thread.
想要在不同的线程中运行每个查询。
Why?为什么?
You really need to learn how windows works internally and what completion ports are.您确实需要了解 Windows 内部如何工作以及完成端口是什么。 Async methods run on NO thread - they just get called into a thread back when they are done.
异步方法在没有线程上运行 - 它们只是在完成后被调用到线程中。 This is based on the windows network model actually - NOT HAVING THREADS WHILE IT WORKS.
这实际上基于 Windows 网络模型 - 没有线程,而它的工作原理。
My problem is the Http GetAsync method only works when it returns a Task, I tried to return a void
我的问题是 Http GetAsync 方法仅在返回任务时才有效,我尝试返回空值
Given that GET Returns something in the task, that would be utterly useless.鉴于 GET 返回任务中的某些内容,那将完全没用。
Your problem is this:你的问题是这样的:
HttpResponseMessage response = await client.GetAsync(query);
HttpResponseMessage response = await client.GetAsync(query);
There is no requirement to AWAIT immediately.无需立即等待。 Start all the async get operations, then start awaiting them.
启动所有异步获取操作,然后开始等待它们。
Really learn basics - you USE async, but you THINK in threads still and thus you do not understand what the async model really gives you.真正学习基础知识 - 您使用异步,但您仍然在线程中思考,因此您不了解异步模型真正为您提供了什么。 The result is a cargo cult like programming totally nullifying the advantages of async, and now asking how to then regain them via threads.
结果是像编程一样的货物崇拜完全取消了异步的优势,现在询问如何通过线程重新获得它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.