简体   繁体   English

C#System.Threading.Timer及其状态对象

[英]C# System.Threading.Timer and its state object

I am writing a C# program that uses System.Threading.Timer to timeout on a UDP socket ReceiveAsync call. 我正在编写一个C#程序,它使用System.Threading.Timer在UDP套接字ReceiveAsync调用上超时。

My program polls a remote device, sending a UDP packet and expecting one in return. 我的程序轮询一个远程设备,发送一个UDP数据包并期待一个回复。

I use the timer in one shot mode calling Timer.Change every time I want a new timeout period. 每次我想要一个新的超时时间时,我都会在一次性模式下使用定时器调用Timer.Change。

For every occurance of a timeout I'd like the timeout handler to have a different piece of information. 对于每次超时的发生,我都希望超时处理程序具有不同的信息。

If I change the object I pass to the Timer on creation it doesn't seem to change when the handler executes. 如果我在创建时更改了传递给Timer的对象,那么当处理程序执行时它似乎没有改变。

Is the only way to do this to destroy the timer and create a new one? 是唯一的方法来摧毁计时器并创建一个新计时器?

Thanks, 谢谢,

Are you passing a struct instead of a class object? 您是否传递结构而不是类对象? Structs are value types, you'll get a copy back of the first version of it. 结构是值类型,您将获得它的第一个版本的副本。 Changes you make will be lost since the state doesn't get passed by ref in the callback. 由于状态未在回调中被ref传递,因此您所做的更改将会丢失。 Using a class instead of a struct is the simple solution. 使用类而不是结构是一个简单的解决方案。

Storing the state object in your own class is another approach. 将状态对象存储在您自己的类中是另一种方法。

您传递的对象可以是一个数组,其中包含您在每次超时时替换的单个元素。

Consider this cheap wrapper: 考虑这个便宜的包装:

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

Please note that using the code above can lead to unexpected behaviour in some rare race conditions. 请注意,使用上述代码可能会在某些罕见的竞争条件下导致意外行为。

使用WaitHandle并锁定以进行同步

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM