RTree and multithreading

I’m trying to multithread a for loop using Parallel.For (this is a C# library). In every loop I want to search for a closest point. Using pointcloud’s closestpoint method seems to work fine (as well as a kdtree library I tested), but not using the rtree class (which seems to be much faster). My guess is because it’s raising an event. I’m not sure how to deal with the event handler to allow multithreading.

Have you tried using a lambda function as event handler?

RTree tree = new RTree();
// fill the tree with data

Parallel.For(0, n, i => 
   BoundingBox searchBox; // define search region based on point or box
   tree.Search(searchbox, (Object sender, RTreeEventArgs args) => 
            // define what happens in the event handler

I got it working by locking the tree search:

lock (locker) {
tree.Search(sphere, searchcallback);

Still, thanks for the reply. I’m going to use the lambda function since it cleans up the code and allows me to set local variables without having to use the tag object.

But performance is even worse than using a normal for loop :frowning:
The cpu is at 90+ % so multithreading seems to be working. Probably locking the rtree search allows only a single search at a time and the extra overhead of parallel.for accounts for the performance loss. Any way around this?

using lock in a parallel process results to run only one single process at the same time, so your process is not parallel now! and a 90% cpu is not a piece of evidence for multithreading, maybe your single process consumes this amount of cpu.
So remove the lock (if it’s possible)