System.Timers.Timer Expired, intermittently interrupted when using Task.Run with async from the Console App

I use a console application, and I have lots of 20 URIs that I need to read, and I found massive speedup by completing all the tasks and doing them in parallel, then sorting the results upon completion in another thread (allowing me to get the next batch).

In the calls I'm currently using, each thread blocks when it receives a response thread, I also see that there is an asynchronous version of the same method GetResponseAsync.

I understand that there are advantages to freeing the thread pool using async Await and Async on the same line instead of locking:

Asynchronous version

return Task.Run(async () =>
{
    var uri = item.Links.Alternate();
    var request = (HttpWebRequest)WebRequest.Create(uri);

    var response = await request.GetResponseAsync();
    var stream = response.GetResponseStream();
    if (stream == null) return null;
    var reader = new StreamReader(stream);
    return new FetchItemTaskResult(reader.ReadToEnd(), index, uri);
});

Blocking version

return Task<FetchItemTaskResult>.Factory.StartNew(() =>
{
    var uri = item.Links.Alternate();
    var request = (HttpWebRequest)WebRequest.Create(uri);

    var response = request.GetResponse();
    var stream = response.GetResponseStream();
    if (stream == null) return null;
    var reader = new StreamReader(stream);
    return new FetchItemTaskResult(reader.ReadToEnd(), index, uri);
});

, System.Timers.Timer ( ).

3500 , ~ 30% .

3800 , , , ( 5%)... , , , 10-15 , Main():

private static void Main(string[] args)
{  
    // snip some code that runs the tasks

    var timer = new System.Timers.Timer(1000);

    timer.Elapsed += (source, e) =>
    {
        Console.WriteLine(DateTime.UtcNow);

        // snip non relevant code
        Console.WriteLine("Commands processed: " + commandsProcessed.Sum(s => s.Value) + " (" + logger.CommandsPerSecond() + " per second)");
    };
    timer.Start();
    Console.ReadKey();
}

, - , async ( async, ) , , , - - , , ?

+4
1

- -

. , , , .. , ThreadPool .

ASP.NET autoConfig="True" , ( ) , . .

, , , :

ThreadPool.SetMinThreads(100, 100);
ServicePointManager.DefaultConnectionLimit = 1000;
+1

All Articles