I have a scenario where I have x amount of queries and I want to run each query in a different thread.
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. 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. I tried using GetAwaiter().GetResult()
, but that also did not work. 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()
}
};
1 Answer 1
want to run each query in a different thread.
Why?
You really need to learn how windows works internally and what completion ports are. 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.
My problem is the Http GetAsync method only works when it returns a Task, I tried to return a void
Given that GET Returns something in the task, that would be utterly useless.
Your problem is this:
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.
-
The reason, I want to run each query in a different thread is because I am trying to replicate an error, On every 7th and 8th run the time slows down drastically and has been consistent. I tried consecutive runs but I was unable to reproduce the error, now I assume the queries run in different threads.user16649086– user1664908611/08/2021 07:57:17Commented Nov 8, 2021 at 7:57
-
1Yeah, you are aware of the ServiceManager class and the limitation of parallel calls? Just saying - if it cuts down after 8 that totally sounds like a limit set there.TomTom– TomTom11/08/2021 10:22:36Commented Nov 8, 2021 at 10:22
await Task.WhenAll(someQueryList.Select(threadAsync))
thread1Create()
function does not create a Thread.