Hi Will,
Its likely that you’ll get concurrency exceptions the way that code is written. These won’t be reported in Rhino as they’re happening on a separate thread, but you’ll be able to see them if you attach a debugger to Rhino.exe and enable CLR exceptions.
Essentially you shouldn’t modify a collection (or object, for that matter) from another thread unless you are using concurrent objects or operations, or are using locks to enforce it. To my knowledge datatrees are not thread safe.
A common way I deal with this is to write data to an array (writing to specific position in an array is a thread safe operation) and then format the data after the loop.
Some examples:
This code is not thread safe. It’s possible that two threads will attempt to write to myList at the same time.
List<int> myList = new List<int>();
Parallel.For(0, 100, i => {
myList.Add(i*i);
});
This code is thread-safe (but inefficient). It uses a lock to ensure only one thread can write to the list at the same time. It’s acceptable when calculating the result takes a long time, but very inefficient if this is for small operations. You’re also not guaranteed to get the output in the same order as the threads may finish out of order.
List<int> myList = new List<int>();
object myListLock = new object();
Parallel.For(0, 100, i => {
int result = i * i; // Let's pretend this is an expensive operation
lock (myListLock)
{
myList.Add(result);
}
});
This code is thread safe. It’s efficient, and it also ensures that the results are in the correct order as they write to the specific array index. We are sure that no other thread is writing to that index as we specify this in the loop.
int[] results = new int[100];
Parallel.For(0, 100, i => {
results[i] = i*i;
});
Essentially, you want to ensure that any operation that affects something outside of the current thread is thread-safe. So it’s fine to make changes to a Brep, as long as no other thread is touching that Brep. Where you have to be careful is how you output the result, as you don’t want multiple threads completing and modifying a data tree at the same time.