Home > Mobile >  Run HttpClient GetAsync in different threads
Run HttpClient GetAsync in different threads

Time:11-11

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()
    }
};

CodePudding user response:

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.

  • Related