C#C
C#3y ago
110 replies
Knuceles

❔ Multithreading an async function

I have an async function that I want to multithread with
n
number of threads, but I get convert error if I initialize the thread with
new Thread(methodName)


From my understanding, I need to use the
.Wait()
method every time I call the
request
method, because it has a
Task
object.

int threadNumber = 5;
Thread[] threads = new Thread[threadNumber];

for (int i = 0; i < threadNumber; i++)
{
  threads[i] = new Thread(request);
  threads[i].Start();
}

for (int i = 0; i < threadNumber; i++) threads[i].Join();


The method
request()
:
static async Task request()
{
  using var client = new HttpClient();
  client.Timeout = TimeSpan.FromSeconds(5);
  var res = await client.GetAsync(URI);
}
Was this page helpful?