kenan
kenan

Reputation: 15

How to start thread for min latency

I am running this c# code.

at some point, I have to web request POST to 3 different servers at the same time. as simultaneously as possible for this, I am using

// t0
System.Threading.Tasks.Task k0 = System.Threading.Tasks.Task.Run(()=>
{ 
   //web request first server  here
});
System.Threading.Tasks.Task k1 = System.Threading.Tasks.Task.Run(()=> 
{
   //we request 2nd server here
});
System.Threading.Tasks.Task k2 = System.Threading.Tasks.Task.Run(()=>
{
   //we request 3rd server here
});

// t1

my problem is it takes 13-15 ms to start the threads. (t1-t0) I am not very good at c#. most of my experience in writing this code and maintaining it. can I decrease the time to start these threads?

Upvotes: 0

Views: 139

Answers (1)

Magnus
Magnus

Reputation: 46929

How about using PostAsync on HttpClient and awaiting all the tasks at the same time.

var responseTask1 = client.PostAsync("http://www.example.com/1", content);
var responseTask2 = client.PostAsync("http://www.example.com/2", content);
var responseTask3 = client.PostAsync("http://www.example.com/2", content);

await Task.WhenAll(responseTask1, responseTask2, responseTask3);

I'm not certain it will be as "simultaneous" as you need, but worth trying out.

Upvotes: 5

Related Questions