Parallel infinite loop in C#

Using Parallel for infinite loop in C#

In .NET framework 4.5 Task Parallel Library of TPL is introduced. It is the same thing as Threading but in additional layer of abstraction. One really useful thing is Parallel class.

The role of Parallel class is similar to ThreadPool, but as I mentioned before, with a higher level of abstraction. It has two mainly used methods:

  • For
  • ForEach

These two are really useful to quicly perform actions on the IEnumerable elements. Of course this is great in case you have infinite number of IEnumerable elements. In case you want to run infinite loop in parallel you need to make a small workaround. Actually this is quite easy with ThreadPool and Semaphore object, but since subject of this article is achieving it with TPL, here is the work around I mentioned before.

First thing is to create infinite IEnumerable. It means whenever the method is invoked it will give the new IEnumerable element. This can be easily done with simple yeald return instead of clasic return which will jump out of the loop.

        private IEnumerable<bool> Infinite()
        {
            while (true)
            {
                yield return true;
            }
        }
    

Now from this method you can easily go ForEach since the IEmurable will be infinite as teh values are created in the infinite loop

 Parallel.ForEach(Infinite(), new ParallelOptions(), new Action<bool>((val) =>
                {
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                }));
    

This is a simple example how the yield return can be transformed easily to an infinite IEnumerable collection and then used in Parallel.ForEach.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article