2012-12-23 35 views
1

我想有一种方法可以在开始另一个呼叫之前等待5秒钟内完成一个方法。这就像它首先显示一个“你好”,然后等待5秒钟,然后显示“世界”,并等待5秒钟再次显示这两个消息。我创建了一个DispatcherTimer方法,但它在等待5秒钟内快速显示两个文本。在启动另一个方法之前等待一个固定的时间

private void AutoAnimationTrigger(Action action, TimeSpan delay) 
    { 
     timer2 = new DispatcherTimer(); 
     timer2.Interval = delay; 
     timer2.Tag = action; 
     timer2.Tick += timer2_Tick; 

     timer2.Start(); 
    } 

    private void timer2_Tick(object sender, EventArgs e) 
    { 
     timer2 = (DispatcherTimer)sender; 
     Action action = (Action)timer2.Tag; 

     action.Invoke(); 

     timer2.Stop(); 
    } 


if (counter == 0) 
       { 
        AutoAnimationTrigger(new Action(delegate { MessageBox.Show("Hello"); }), TimeSpan.FromMilliseconds(5000)); 
        AutoAnimationTrigger(new Action(delegate { MessageBox.Show("World"); }), TimeSpan.FromMilliseconds(5000)); 

       } 

我该错过什么或做错了什么?

edit___

ThreadPool.QueueUserWorkItem(delegate 
     { 
      //Thread.Sleep(5000); 

      Dispatcher.Invoke(new Action(() => 
      { 
       TranslateX(4); 
       TranslateY(-0.5); 

      }), DispatcherPriority.Normal); 


      //Dispatcher.BeginInvoke(new Action(() => 
      //{ 
      // TranslateY(0.5); 
      //}), DispatcherPriority.Normal); 

     }); 

然后我就简单地调用方法..

+0

你能准确地知道你使用的是什么C#版本吗?在显示消息时,应用程序的其余部分是否仍在运行? – Ucodia

+0

c#4.0 ..我很抱歉.. messagebox只是一种方式来显示我的代码正在运行,仅用于测试,实际上我想在kinect设备未检测到任何骨架时为模型创建动画。 – user1884304

回答

3

你叫AutoAnimationTrigger这将覆盖timer2,您声明为类变量的两倍。 多个不同动作简单的解决方案将使用Thread.Sleep

ThreadPool.QueueUserWorkItem(delegate 
{ 
    Thread.Sleep(5000); 
    MessageBox.Show("Hello"); 
    Thread.Sleep(5000); 
    MessageBox.Show("World"); 
    Thread.Sleep(5000);  
    MessageBox.Show("Hello World"); 
}); 
+0

谢谢。这个完美的作品!再次感谢〜 – user1884304

+0

@ user1884304欢迎:) – VladL

+0

嗨..我再次怀疑..我可以等待dispatcher.invoke完全运行并完成,然后才启动下一个dispatcher.invoke? Thread.sleep不成功,我的案例..我编辑我的原始帖子的代码..任何想法?谢谢。 – user1884304

0

只需使用Thread.Sleep(5000)之间有两个方法调用。

+1

为什么要重复43分钟前别人说的话? – Adam

+1

为什么要使用threadpool? @codesparkle –

相关问题