Assuming you can use .NET 4, I will show you how to do this in a much cleaner way that avoids changing the volatile state across threads (and thus avoids blocking).
class PointCloud { public Point3DCollection Points { get; private set; } public event EventHandler AllThreadsCompleted; public PointCloud() { this.Points = new Point3DCollection(1000); var task1 = Task.Factory.StartNew(() => AddPoints(0, 0, 192)); var task2 = Task.Factory.StartNew(() => AddPoints(1, 193, 384)); var task3 = Task.Factory.StartNew(() => AddPoints(2, 385, 576)); Task.Factory.ContinueWhenAll( new[] { task1, task2, task3 }, OnAllTasksCompleted,
Consuming this class is easy:
// On main WPF UI thread: var cloud = new PointCloud(); cloud.AllThreadsCompleted += (sender, e) => MessageBox.Show("all threads done! There are " + cloud.Points.Count.ToString() + " points!");
Explanation of this method
Think of streaming differently: instead of trying to synchronize access to streams with shared data (like your list of points), do the hard work in the background thread instead, but don't mutate any general state (like don't add nothing to the list of points). For us, this means that we iterate over X and Y and find Z, but do not add them to the list of points in the background thread. Once we create the data, let the UI thread know that we are done and let it take care of adding items to the list.
This method has the advantage that it does not use any mutable state - only 1 thread accesses a collection of points. This also has the advantage of not requiring any locks or explicit synchronization.
This has another important characteristic: your UI thread will not block. This is usually good; you do not want your application to look frozen. If user interface thread blocking is a requirement, we will have to rework this solution a bit.
source share