Click here to Skip to main content
15,891,567 members
Articles / Programming Languages / C#
Technical Blog

PLinq and source IEnumerable thread safety

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 Sep 2012Apache 7.8K   4  
PLinq and source IEnumerable thread safety

As I discovered that the source IEnumerable is called by PLINQ from multiple threads, it made me thinking: how can it possibly work? E.g. when someone writes code like this:

Enumerable.Range(1,1000).AsParallel()...

the Range iterator must keep its current state in some variable. If this state is accessed from multiple threads, how are race conditions avoided? Here are my findings in order:

1. Enumerable.Range() returns an IEnumerable<int>. This enumerable’s GetEnumerator() will return different enumerators for different threads. This appears to be a built-in feature of enumerables generated from yield return keyword. Reflector is my witness. Proof link.

Each enumerator, however, is not thread safe and does not have any locking code.

2. AsParallel() calls GetEnumerator() only once, and then uses it from multiple threads, so the above protection does not work.

3. Stephen Toub of Microsoft says, that as IEnumerable is inherently thread unsafe, PLINQ has locking built in.

4. As per Reflector it appears to be implemented in the PartitionedDataSoruce<T>.MoveNext() method.

So, relax folks. Your enumerator can and will be thread unsafe, PLINQ has its own locks to take care of that.

This article was originally posted at http://www.ikriv.com/blog?p=1065

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

Comments and Discussions

 
-- There are no messages in this forum --