My understanding is if I use async, the thread makes the web request and moves on. When the response comes back another thread picks it up from there. So there are a lesser number of tied up threads sitting idle. Wouldn't this mean the maximum number of live threads would go down? But in the example below, the code that doesn't use async ends up using lesser number of threads. Can some one explain why?
Code without async (uses lesser threads):
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
namespace NoAsync
{
internal class Program
{
private const int totalCalls = 100;
private static void Main(string[] args)
{
for (int i = 1; i <= totalCalls; i++)
{
ThreadPool.QueueUserWorkItem(GoogleSearch, i);
}
Thread.Sleep(100000);
}
private static void GoogleSearch(object searchTerm)
{
Thread.CurrentThread.IsBackground = false;
string url = @"https://www.google.com/search?q=" + searchTerm;
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
WebRequest wr = WebRequest.Create(url);
var httpWebResponse = (HttpWebResponse) wr.GetResponse();
var reader = new StreamReader(httpWebResponse.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
//Console.WriteLine(responseFromServer); // Display the content.
httpWebResponse.Close();
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
}
}
}
Code with async (uses more threads)
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace AsyncAwait
{
internal class Program
{
private const int totalCalls = 100;
private static DateTime start = System.DateTime.Now;
private static void Main(string[] args)
{
var tasks = new List<Task>();
for (int i = 1; i <= totalCalls; i++)
{
var searchTerm = i;
var t = GoogleSearch(searchTerm);
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Hit Enter to exit");
Console.ReadLine();
}
private static async Task GoogleSearch(object searchTerm)
{
Thread.CurrentThread.IsBackground = false;
string url = @"https://www.google.com/search?q=" + searchTerm;
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
HttpContent content = response.Content;
content.Dispose();
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
Console.WriteLine("TimeSpan consumed {0}", System.DateTime.Now.Subtract(start));
}
}
}
}
}
I do understand my results include unmanaged threads. But shouldn't the total number of threads still be lower?
Update: I updated the async call with the code provided by Noseratio