我有一个WPF应用程序,它启动了3个线程,并需要等待它们完成。我在这里读了很多帖子来处理这个问题,但似乎没有一个是解决线程代码调用Dispatcher.Invoke或Dispatcher.BeginInvoke的情况。如果我使用线程的Join()方法或ManualResetEvent,线程将阻塞在Invoke调用上。以下是一个简化的代码片段,它看起来很丑陋,但似乎能够工作:
class PointCloud
{
private Point3DCollection points = new Point3DCollection(1000);
private volatile bool[] tDone = { false, false, false };
private static readonly object _locker = new object();
public ModelVisual3D BuildPointCloud()
{
...
Thread t1 = new Thread(() => AddPoints(0, 0, 192));
Thread t2 = new Thread(() => AddPoints(1, 193, 384));
Thread t3 = new Thread(() => AddPoints(2, 385, 576));
t1.Start();
t2.Start();
t3.Start();
while (!tDone[0] || !tDone[1] || !tDone[2])
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
Thread.Sleep(1);
}
...
}
private void AddPoints(int scanNum, int x, int y)
{
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
z = FindZ(x, y);
if (z == GOOD_VALUE)
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
Point3D newPoint = new Point3D(x, y, z);
lock (_locker)
{
points.Add(newPoint);
}
}
);
}
}
}
tDone[scanNum] = true;
}
}
from the main WPF thread...
PointCloud pc = new PointCloud();
ModelVisual3D = pc.BuildPointCloud();
...
如何改进这段代码,有任何想法都非常感谢。这似乎是一个非常普遍的问题,但我似乎无法在任何地方找到正确的解决方法。