I dont quite understand async/await benefit compare to threading.
In case inside a method, I have an operation without async/await version that consume some time like 20ms in the middle of other async operations.
Calling this method 1000 times, since async/await only execute inside one thread, it will comsume at least 20ms x 1000 time in my test (using Thread.Sleep to simulate).
Is there any misunderstanding about async/await?
public void Start()
{
Task[] task = new Task[500];
for (int i = 0; i < 500; i++)
{
task[i] = AsyncGet();
}
await Task.WhenAll(task);
}
public async Task<bool> AsyncGet()
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.example.com");
req.Method = "GET";
using(HttpWebResponse res = (HttpWebResponse)await req.GetResponseAsync())
{
Thread.Sleep(20);//Simulate an operation without async/await version that consume a little bit time
using (Stream responseStream = res.GetResponseStream())
{
StreamReader sr = new StreamReader(responseStream, Encoding.ASCII);
string resp = await sr.ReadToEndAsync();
}
}
}
Update question:
If I have a need to do some non-async/await operation like manipulating json after getting http response using external library. What is the best practice to avoid the time wasted?