【问题标题】:Firing method on interval with System.Threading.Timer in winForm C#winForm C#中System.Threading.Timer的间隔触发方法
【发布时间】:2011-08-02 04:55:44
【问题描述】:

我想做的是使用 System.Threading.Timer 执行一个有间隔的方法。 我的示例代码看起来像这样。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        System.Threading.Timer t1 = new System.Threading.Timer(WriteSomething, null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10));

    }
    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Clear();
    }

    public void WriteSomething(object o)
    {

        textBox1.Text = "Test";
    }
}

}

这不是假设每 10 秒执行一次 WriteSomething 方法吗?实际发生的是,当我运行我的应用程序并在 10 秒后应用程序关闭时执行了 WriteSomething。认为我误解了它是如何工作的,谁能告诉我如何使用 System.Threading.Timer 来做到这一点。

提前致谢,非常欢迎代码示例

【问题讨论】:

标签: c# methods timer intervals


【解决方案1】:

更有可能的情况是它在 10 秒后崩溃。您不能触摸回调中的任何控件,它在错误的线程上运行。您必须使用 Control.BeginInvoke()。这使得使用 System.Threading.Timer 而不是 System.Windows.Forms.Timer完全没有意义

务实。将其设置为 100 毫秒,这样您就不会在等待崩溃时长出胡须。而且不要使用异步定时器来更新UI,没用。

【讨论】:

  • 对使用拖放计时器不感兴趣。想要改为编码。
  • 我不能,这是错误的代码。一步一步:将一个计时器从工具箱放到表单上。双击它。
  • 好的,打开 Designer.cs 文件,剪切粘贴设计器生成的代码。
  • 使用 System.Windows.Forms.Timer 的代码只是...请参阅下面的答案...更容易将代码放入答案中。
【解决方案2】:

重申一下 Hans 所说的,在 WinForms 应用程序中,所有 GUI 元素本质上都不是线程安全的。 Control 类上的几乎所有方法/属性只能在创建 GUI 的线程上调用。 System.Threading.Timer 在线程池线程上调用其回调,而不是在您创建计时器的线程上(请参阅下面的 MSDN 参考)。正如 Hans 所说,您可能需要一个 System.Windows.Forms.Timer,它会在正确的线程上调用您的回调。

您始终可以使用代码验证是否可以调用控件上的方法(确保您在正确的线程上):

System.Diagnostics.Debug.Assert(!InvokeRequired);

在您的事件处理程序中。如果断言发生故障,则说明您处于无法修改此控件的线程上。

引用 MSDN 帮助 System.Threading.Timer 关于您在构造函数中传递的回调方法:

该方法不会在 创建计时器的线程;它 在 ThreadPool 线程上执行 由系统提供。

【讨论】:

    【解决方案3】:

    仅供参考,System.Windows.Forms 计时器不允许您在代码中创建(它不仅仅是“拖放”计时器)。代码:

    构造函数代码:

      System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
      timer.Tick += OnTimerTick;
      timer.Interval = 10000;
      timer.Start();
    

    事件处理程序:

      private void OnTimerTick(object sender, EventArgs e)
      {
        // Modify GUI here.
      }
    

    【讨论】:

    • +1 用于跟进,-1/4 用于不阻止胡须生长。网 1.
    【解决方案4】:

    常见错误:需要将计时器变量保留为类成员,因为垃圾收集器可能会杀死它。

    【讨论】:

      猜你喜欢
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多