0

很抱歉这个问题可能太简单了,但我不知道如何实现。如果某个方法在一定时间内没有被调用,我需要引发一个事件(当我收到这个事件时,我会尝试解决问题。这是一种连接问题,我需要得到通知以尝试解决它 - 我将改变连接方式。)

public void MethodThatShouldBeCalledFrequently // acutally datagram from UDP received
{
    // if not called for 5 seconds than raise event 
}
public event EventHandler</*no parameters*/> MethodNotCalledForFiveSeconds; // connection problem, switch from UDP to TCP
4

2 回答 2

0

也许您可以在调用 MethodThatShouldBeCalledFrequently 时使用一个标志并将其设置为 true。

     bool wasCalled = false;
    public void MethodThatShouldBeCalledFrequently // acutally datagram from UDP received
     {
        wasCalled = true;
      }

使用另一种方法每 5 秒检查一次标志是真还是假,如果为假,则引发事件。

于 2012-04-08T07:31:19.993 回答
0

那这个呢?

public class Program
{
    private Timer timer;

    public Program()
    {
       InitializeTimer();
       StartTimerFromBeginning();
    }

    public void MethodThatShouldBeCalledFrequently()
    {
       StartTimerFromBeginning();
    }

    public event EventHandler MethodNotCalledForFiveSeconds;

    private void InitializeTimer()
    {
       timer = new Timer(5000);
       timer.Elapsed += HandleTimerElapsed;
    }

    private void StartTimerFromBeginning()
    {
       timer.Stop();
       timer.Start();
    }

    private void HandleTimerElapsed(object sender, ElapsedEventArgs e)
    {
       MethodNotCalledForFiveSeconds(this, EventArgs.Empty);
    }
}
于 2012-04-08T07:38:08.827 回答