【问题标题】:Wait for a fixed time before start another method在开始另一个方法之前等待固定时间
【发布时间】:2013-07-19 23:29:54
【问题描述】:

我希望有一种方法可以在开始另一个调用之前等待一个方法在 5 秒内完成。就像它首先显示“Hello”然后等待 5 秒,然后显示“World”并再等待 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));

                }

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

编辑___

 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);

        });

然后我只是简单地调用方法..

【问题讨论】:

  • 您能准确说明您使用的是哪个 C# 版本吗?当您显示消息时,应用程序的其余部分是否应该继续运行?
  • c# 4.0.. 对不起.. 消息框只是我显示我的代码正在运行的一种方式,只是为了测试,实际上我想在 kinect 设备未检测到时为模型设置动画任何骨架..

标签: c# wpf threadpool dispatcher


【解决方案1】:

您调用 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");  
 });

【讨论】:

  • 嗨..我又有疑问了..我怎样才能等待 dispatcher.invoke 完全运行并完成,然后才开始下一个 dispatcher.invoke? Thread.sleep 对我的情况不成功..我已经从我的原始帖子中编辑了我的代码..有什么想法吗?谢谢。
  • 我的意思是例如向左翻译,因为翻译需要一些时间才能完成。完成左翻译后,我将要向下翻译,然后向上和向右翻译。
  • 为什么需要 Dispatcher.Invoke ?
  • 因为如果我直接调用 translateX 会出现异常错误——“调用线程无法访问这个对象,因为不同的线程拥有它”。
  • @user1884304 这个异常只发生在调试器中吗?
【解决方案2】:

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

【讨论】:

  • 为什么要重复别人 43 分钟前所说的话?
猜你喜欢
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 2016-11-26
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多