每秒加载新图像
我需要加载每秒(或两个)新图像。
以下代码不起作用:
System.Threading.Thread.Sleep(2000); this.Image_LoadImage.Source = new BitmapImage(new Uri(@"D:\\connect2-1.gif")); System.Threading.Thread.Sleep(2000); this.Image_LoadImage.Source = new BitmapImage(new Uri(@"D:\\connect3-1.gif"));
我看到的是该应用程序睡眠4秒,然后出现第二个图像。
我该怎么做? 谢谢。
使用计时器
private System.Threading.Timer timer; public MainWindow() { InitializeComponent(); timer = new System.Threading.Timer(OnTimerEllapsed, new object(), 0, 2000); } private void OnTimerEllapsed(object state) { if (!this.Dispatcher.CheckAccess()) { this.Dispatcher.Invoke(new Action(LoadImages)); } } private bool switcher; private void LoadImages() { string stringUri = switcher ? @"D:\\connect2-1.gif" : @"D:\\connect3-1.gif"; this.Image_LoadImage.Source = new BitmapImage(new Uri(stringUri)); switcher = !switcher; }
使用计时器。
调用线程hibernate会阻止UI线程。 找到此链接 :
我想你的代码驻留在一个函数中,该函数在主线程上执行。 因此,在函数返回之前,UI不会更新。
在那时,你将留下你的函数返回时最新的状态( 这就是为什么你只看到你设置的最后一张图片 )。
另外,请注意,通过在函数中发出Sleep()
请求,您实际上是在阻止应用程序的主线程(或者您的函数运行的任何线程,但很可能这是您的主线程)。 在hibernate期间,您的应用程序不会简单地响应任何内容,您的UI将冻结。
您可能决定使控件无效( Control.Refresh()
, Control.Invalidate()
, Control.Update()
, Control.Refresh()
, Application.DoEvents()
)但这些通常是黑客攻击,除非正确使用。
使用Timer
是一种选择。 虽然,在您的具体情况下,简单地使用动画GIF可能是最好的解决方案。
请注意,如果您决定使用计时器,则 System.Windows.Forms.Timer
与其他计时器之间存在非常重要的差异 。 System.Windows.Forms.Timer
将在您的主线程上尽可能System.Windows.Forms.Timer
运行(因此,与UI控件交互是安全的,因为您将从同一个线程执行此操作;但另一方面,它可能会火稍有延迟)。 相反,如果您要使用其他计时器,则无法在不违反重要规则的情况下直接访问UI控件。 有关它的更多信息: 比较.NET Framework类库中的Timer类
请参阅: 从UI线程强制GUI更新
并且: 使用C#在表单中动画Gif
更改源代码后尝试刷新()控件。