如果在最后5秒没有调用方法的话怎么举事件?

时间:2012-04-08 07:24:49

标签: c#

很抱歉这可能是一个太简单的问题,但我不知道如何实现这个。如果某些方法没有被调用一段时间我需要提出一个事件(当我收到这个事件时,我会尝试解决问题。这是一种连接问题,我需要通知它,试图解决它 - 我将改变连接方法。)

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

2 个答案:

答案 0 :(得分:0)

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

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

如果标志为真或假,则使用另一种方法每5秒检查一次,如果标志为假,则提高事件。

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