我正在使用WPF和C#创建应用程序。我想要做的是在画布上打印很多形状,在按下按钮之间有一段时间。在我按下按钮的那一刻,一切都会立即弹出。我试图在每次“打印”之间暂停一段时间,但这没有用,只需要更长的时间才能立刻完成任务。我想要实现的是,每次弹出一个形状,然后让它们间隔0.5秒。代码如下:
private void Create_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
for (int i = 0; i < 50; i++)
{
Thread.Sleep(500);
Path f = FlowerFactory.createFlower(FlowerBP, true);
Canvas.SetLeft(f, random.Next(0, 1650));
Canvas.SetTop(f, random.Next(0,1000));
DrawBoard.Children.Add(f);
}}
答案 0 :(得分:3)
首先,您需要在后台线程中运行循环,以便它不会阻止UI更新;第二,将UI呈现任务发送回UI线程。首先,您可以使用Task.Factory.StartNew
,然后使用Dispatcher.Invoke
:
Random random = new Random();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 50; i++)
{
Thread.Sleep(500);
Dispatcher.Invoke(DispatcherPriority.Render, new Action(() =>
{
Path f = FlowerFactory.createFlower(FlowerBP, true);
Canvas.SetLeft(f, random.Next(0, 1650));
Canvas.SetTop(f, random.Next(0,1000));
DrawBoard.Children.Add(f);
}));
}
});
答案 1 :(得分:1)
睡觉负责GUI的主线程是错误的决定。
尝试使用DispatchTimer。例如:
DispatcherTimer m_dispatcherTimer = new DispatcherTimer();
int m_count = 50;
private void Init()
{
m_dispatcherTimer.Tick += new EventHandler(OnTick);
m_dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
}
private void Create_Click(object sender, RoutedEventArgs e)
{
m_count = 50;
m_dispatcherTimer.Start();
}
private void OnTick(object sender, EventArgs e)
{
// Draw your shapes here
if(0>=--m_count)
{
m_dispatcherTimer.Stop();
}
}
答案 2 :(得分:0)
using System.Reactive.Concurrency;
using System.Reactive.Linq;
...
var subscription = Observable.Interval(TimeSpan.FromSeconds(0.5)).Take(50).Subscribe(x=>CreateRandomFlower);