blez
blez

Reputation: 5037

How to make timer with timeout

I have a slow method, while executing it on timer (System.Timers.Timer). It sometimes gets longer to execute than the timer's timeout, which causes the timer to wait. I want while I set the timer for 30ms for example, after 30ms, to reset the method, not wait. What kind of timer should I use?

EDIT:

void OnTimerElapsed() {
      SomeMethod(args1);
      SomeMethod(args2);
      SomeMethod(args3);
}

SomeMethod is located in another assembly. It's a sync method which requests data from another application. I don't know why it sometimes hangs. That causes the timer to pause until SomeMethod() continues.

Upvotes: 0

Views: 5691

Answers (1)

Jalal Said
Jalal Said

Reputation: 16162

Use the System.Timers.Timer and set the its AutoReset to false, and only start it when the previous elapsed finished or at your custom condition. Here is the pattern that I use:

private System.Timers.Timer _timer = new System.Timers.Timer();
private volatile bool _requestStop = false;

private void InitializeTimer()
{
    _timer.Interval = 100;
    _timer.Elapced += OnTimerElapced;
    _timer.AutoReset = false;
    _timer.Start();
}

private void OnTimerElapced(object sender, System.Timers.TimerEventArgs e)
{
    //_timer.Stop();//if AutoReset was not false

    //do work....

    if (!_requestStop)
    {
        _timer.Start();//restart the timer
    }
}

private void Stop()
{
    _requestStop = true;
    _timer.Stop();
}

private void Start()
{
    _requestStop = false;
    _timer.Start();
}

Edit: If you like to watch the timer and if the operation takes longer time then you should not use timer in the first place, instead use wrap your operation in a new thread and use MaunalResetEvent, use its WaitOne method to specify the timeout, if the timeout occurs then stop or about the operation.

Upvotes: 2

Related Questions