Grasshopper

algorithmic modeling for Rhino

C# Example: For-loop in parallel execution and the "lock" statement

Hello,

I noticed that a lot of people coding with python are using the parallel- library, whereas I never see people using multithreading in C# or VB.

This is probably because most people don't know how to make use of the current asynchrony tools provided by dot.net's  "System.Threading" library.

Here a quick example for a parallel loop:

var result = new  List<object>();

System.Threading.Tasks.Parallel.For(0, points.Count, i =>
    {    

       // do something in here  
      

       // append whatever you did to the result list like this:

       lock(result)

          result.Add(whatever)


    }
    
);

the "lock"-keyword prevents simultaneous access to an object,

which is important when in asynchrony mode.

  

Here is a quick example:

  

Views: 3035

Replies to This Discussion

You're better off using a Concurrent collection rather than continually locking on a List<T>. You cannot guarantee that the order of items added to the list is the same as the order in which the loop runs anyway, so using a ConcurrentBag would absolve you from locking responsibilities.

I'm not surprised though that people don't use the C# parallel loops, it's one of the worst notations in the entirety of C# in my opinion. It seems to me that C# is rapidly becoming an odd sock drawer of language paradigm experiments. Unless they get their act together and start deprecating a lot of the old stuff which has been superseded by better alternatives (I'm looking at you ArrayList) we'll end up with a language too big and complicated to learn.

Yeah I know, for all my criticism I don't really have a good solution either. I think the main problems with C# today is that core concepts such as immutability and asynchronicity are not part of the bottom-most layer of the language spec. I suspect these shortcomings prevent the compiler programmers from really implementing parallelism on a completely behind-the-scenes level.

I've designed some classes for GH2 that help multi-threading processes that operate on input/output arrays. However it requires implementors to create derived classes, so it's not anywhere near as 'light' as a loop notation.

While I consider concurrent collections, locking, Interlock class and similar quite easy to use, I totally can't get my head around multithreaded "events"... IMHO, what msdn lacks the most is a low/mid - level pseudocode of what all of those functions/classes do. This is certainly one of the most black-boxed topics there.. 

RSS

About

Translate

Search

Photos

  • Add Photos
  • View All

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service