Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this code, it is the skeleton of larger functionality stripped down to prove the problem:

        var tasks = Enumerable.Range(0, 10)
            .Select(laneNo => Task.Run(() => Console.WriteLine($"Starting generator for lane {laneNo}")));

        for(int r=0; ;++r)
        {
            Task.Delay(TimeSpan.FromSeconds(3)).Wait();

            Console.WriteLine($"Iteration {r} at {DateTime.Now}");
        }

I never see "Starting generator" printed to Console but I do see the iteration fire every 3 seconds - something is causing those tasks not to progress (in the real code they run for a significant period but removing that doesn't affect the problem).

Why are the first bunch of Tasks not running? My theory is it's related to Task.Delay?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your linq-statment is never materialized. Linq-operators like Select, Where, OrderBy, etc work as building blocks that you chain together but they are not executed until you run it through a foreach or use operators which do not return enumerables, like ToArray, ToList, First, Last etc.

If you call ToList at the end you should see all of the tasks executing but if you only call First you should see only a single one because the iteration of your original Range will then terminate after first element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...