C # System.Threading.Timer and its state object

I am writing a C # program that uses System.Threading.Timer to timeout a call to ReceiveAsync on a UDP socket.

My program checks the remote device, sends a UDP packet and waits for it in response.

I use the timer in single shot mode, calling Timer.Change every time I want a new waiting period.

For each timeout case, I would like the timeout handler to have different information.

If I modify the object that I pass to Timer when I create it, it does not change when the handler executes.

Is this the only way to do this to destroy the timer and create a new one?

Thank,

+3
source share
4 answers

? , . , , , ref . - .

- .

+1

, , , .

0

:

sealed class TimerWrapper : IDisposable
{
    readonly Timer timer;

    object State { get; set; }

    public TimerWrapper(TimerCallback callback) 
    {
        timer = new Timer(delegate { callback(State); });
    }

    public void Change(object state, TimeSpan dueTime, TimeSpan period)
    {
        timer.Change(dueTime, period);
        State = state;
    }

    public void Dispose()
    {
        timer.Dispose();
    }
}

, .

0

WaitHandle

0

Source: https://habr.com/ru/post/1742262/


All Articles