【问题标题】:Wait with return statement until Timer elapsed等待返回语句,直到 Timer 结束
【发布时间】:2012-10-23 09:08:03
【问题描述】:

我有一个返回 bool 值的方法,但应该等待返回值,直到 System.Timers.Timer 引发 elapsed 事件,因为我要返回的值是在计时器的 elapsed 事件中设置的。

public static bool RecognizePushGesture()
{
    List<Point3D> shoulderPoints = new List<Point3D>();
    List<Point3D> handPoints = new List<Point3D>();
    shoulderPoints.Add(Mouse.shoulderPoint);
    handPoints.Add(Mouse.GetSmoothPoint());
    Timer dt = new Timer(1000);
    bool click = false;

    dt.Elapsed += (o, s) =>
    {
        shoulderPoints.Add(Mouse.shoulderPoint);
        handPoints.Add(Mouse.GetSmoothPoint());
        double i = shoulderPoints[0].Z - handPoints[0].Z;
        double j = shoulderPoints[1].Z - handPoints[1].Z;
        double k = j - i;
        if (k >= 0.04)
        {
            click = true;
            dt.Stop();
        }
    };

    dt.Start();

    //should wait with returning the value until timer raises elapsed event
    return click;
}

谢谢,蒂姆

【问题讨论】:

  • 如果你想基本上同步做某事(阻塞直到它完成)你为什么要启动一个计时器?这里的上下文是什么? (GUI,不是 GUI,什么样的 GUI?)
  • 如果它只会被触发一次......你为什么要使用计时器?如果你不介意阻塞当前线程,你可以使用 Sleep() (或者什么都不用)。如果您在等待第一个“elapsed”事件时可能会做一些其他处理,为什么不使用线程/任务(完成并行工作后您将加入)?
  • 好的,上下文是 Windows 的 Kinect,我需要延迟 1 秒比较手和肩关节的 z 坐标
  • 我不希望 RecognizePushGesture() 阻止我当前的线程
  • @TimT RecognizePushGesture() 调用者将等待其返回值,因此它必须等待。如果不应该,您最好也重构调用者(并且在这种情况下不要使用计时器):使其异步并用简单的 Thread.Sleep(1000) 替换计时器。

标签: c# multithreading timer wait


【解决方案1】:

使用 AutoResetEvent

public static bool RecognizePushGesture()
    {
        AutoResetEvent ar = new AutoResetEvent(false);
        List<Point3D> shoulderPoints = new List<Point3D>();
        List<Point3D> handPoints = new List<Point3D>();
        shoulderPoints.Add(Mouse.shoulderPoint);
        handPoints.Add(Mouse.GetSmoothPoint());
        Timer dt = new Timer(1000);
        bool click = false;
        dt.Elapsed += (o, s) =>
        {
            shoulderPoints.Add(Mouse.shoulderPoint);
            handPoints.Add(Mouse.GetSmoothPoint());
            double i = shoulderPoints[0].Z - handPoints[0].Z;
            double j = shoulderPoints[1].Z - handPoints[1].Z;
            double k = j - i;
            if (k >= 0.04)
            {
                click = true;
                dt.Stop();
            }
            ar.Set();
        };
        dt.Start();

        //should wait with returning the value until timer raises elapsed event
        ar.WaitOne();
        return click;
    }

【讨论】:

  • ok 问题已解决,刚刚在自己的线程中启动了 RecognizePushGesture()。这不再阻止我当前的线程感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多