c# - 重置 System.Timers.Timer 以防止 Elapsed 事件

标签 c# asp.net static timer

我正在尝试使用 Timer触发事件以通过网络发送数据。我创建了一个简单的类来调试。基本上我有一个 List<string>我想寄。我希望发生以下情况:

  1. 将字符串添加到 List
  2. 开始Timer 10 秒
  3. 将第二个字符串添加到 List之前Timer.Elapsed
  4. 重启Timer 10 秒后返回。

到目前为止我有这个:

public static List<string> list;
public static Timer timer;
public static bool isWiredUp = false;

public static void Log(string value) {
    if (list == null) list = new List<string>();
    list.Add(value);

    //this does not reset the timer, elapsed still happens 10s after #1
    if (timer != null) {
        timer = null;
    }

    timer = new Timer(10000);
    timer.Start();
    timer.Enabled = true;
    timer.AutoReset = false;

    if (!isWiredUp) {
        timer.Elapsed += new ElapsedEventHandler(SendToServer);
        isWiredUp = true;
    }
}

static void SendToServer(object sender, ElapsedEventArgs e) {
    timer.Enabled = false;
    timer.Stop();
}

有什么想法吗?

最佳答案

您可以使用 Stop函数后紧跟 Start “重启”定时器的功能。使用它你可以创建 Timer第一次创建类时,连接 Elapsed 事件,然后在添加项目时只调用这两个方法。它将启动或重新启动计时器。请注意,调用 Stop在尚未启动的计时器上什么也不做,它不会抛出异常或导致任何其他问题。

public class Foo
{
    public static List<string> list;
    public static Timer timer;
    static Foo()
    {
        list = new List<string>();
        timer = new Timer(10000);
        timer.Enabled = true;
        timer.AutoReset = false;
        timer.Elapsed += SendToServer;
    }

    public static void Log(string value)
    {
        list.Add(value);
        timer.Stop();
        timer.Start();
    }

    static void SendToServer(object sender, ElapsedEventArgs e)
    {
        //TODO send data to server

        //AutoReset is false, so neither of these are needed
        //timer.Enabled = false;
        //timer.Stop();
    }
}

请注意,而不是使用 List您很可能想使用 BlockingCollection<string>反而。这有几个优点。首先,Log如果从多个线程同时调用,方法将起作用;多个并发日志可能会破坏列表。这也意味着 SendToServer可以在添加新项目的同时将项目从队列中取出。如果您使用 List你需要 lock所有对列表的访问(这可能不是问题,但不是那么简单)。

关于c# - 重置 System.Timers.Timer 以防止 Elapsed 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14861047/

相关文章:

c# - OWIN AuthenticationOptions 在运行时在 mvc5 应用程序中更新

c# - 从 FetchXML 访问第二级链接实体

c# - 在C#中将表格插入到word中

c# - 缓存 Linq 查询问题

c - 动态分配 C 数组的大小不应该出错吗?

c# - 当 MessageContract 位于我的 WCF 服务中时,为什么代理生成的代码会创建一个新类?

c# - 封装 Action<T> 和 Func<T>?

javascript - 格式化数字和日期的困境

java - 从另一个类的静态方法初始化Spring bean,给出方法参数?

eclipse - Eclipse 动态 Web 项目中静态文件目录的放置位置