Click here to Skip to main content
Click here to Skip to main content

PLinq and source IEnumerable thread safety

, 3 Sep 2012
Rate this:
Please Sign up or sign in to vote.
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.

License

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

About the Author

Ivan Krivyakov
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 --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 3 Sep 2012
Article Copyright 2012 by Ivan Krivyakov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid