【发布时间】:2017-04-25 06:12:53
【问题描述】:
在我的程序中,我有一个对象数组,我想延迟打印每个对象一次。
现在这是我的 Draw() 函数:
public void Draw()
{
myCanvas.Children.Clear();
foreach (Square Sq in MyDrawings)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
sq.Draw();
}));
}
}
我的 sq.draw() 函数,当前绘制一个矩形,并将其添加到画布中:
rect = new Rectangle
{
Stroke = Brushes.Black,
StrokeThickness = 0.5,
Fill = Brushes.Black,
Height = Width,
Width = Width
};
Canvas.SetTop(rect, x * Width);
Canvas.SetLeft(rect, y * Width);
Form.myCanvas.Children.Add(rect);
我尝试添加一个 Thread.Sleep();在主 Draw() 函数中,但它似乎阻塞了 UI 线程,当它解除阻塞时,整个 Array 已被绘制。
我也尝试使用 DispatcherTimer,但我不知道要添加什么延迟,因为我想打印每个对象,而不是基于时间。
固定代码:
public void Draw()
{
myCanvas.Children.Clear();
foreach (Square Sq in MyDrawings)
{
Task.Run(() =>
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
sq.Draw();
}));
Thread.Sleep(100);
});
}
}
【问题讨论】: