0

我有一个返回 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;
}

谢谢,蒂姆

4

1 回答 1

0

使用 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;
    }
于 2012-10-23T09:17:00.070 回答