Parallel features in .Net 4.0

Posted by Jonathan.Peppers on Stack Overflow See other posts from Stack Overflow or by Jonathan.Peppers
Published on 2010-05-05T18:26:56Z Indexed on 2010/05/05 18:38 UTC
Read the original article Hit count: 93

Filed under:
|
|
|

I have been going over the practicality of some of the new parallel features in .Net 4.0.

Say I have code like so:

foreach (var item in myEnumerable)
    myDatabase.Insert(item.ConvertToDatabase());

Imagine myDatabase.Insert is performing some work to insert to a SQL database.

Theoretically you could write:

Parallel.ForEach(myEnumerable, item => myDatabase.Insert(item.ConvertToDatabase()));

And automatically you get code that takes advantage of multiple cores.

But what if myEnumerable can only be interacted with by a single thread? Will the Parallel class enumerate by a single thread and only dispatch the result to worker threads in the loop?

What if myDatabase can only be interacted with by a single thread? It would certainly not be better to make a database connection per iteration of the loop.

Finally, what if my "var item" happens to be a UserControl or something that must be interacted with on the UI thread?

What design pattern should I follow to solve these problems?

It's looking to me that switching over to Parallel/PLinq/etc is not exactly easy when you are dealing with real-world applications.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET