等待return语句,直到Timer过去

时间:2012-10-23 09:08:04

标签: c# multithreading timer wait

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

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

谢谢,蒂姆

1 个答案:

答案 0 :(得分: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;
    }