gpt4 book ai didi

c# - 在 winForm C# 中使用 System.Threading.Timer 间隔触发方法

转载 作者:行者123 更新时间:2023-11-30 13:28:27 28 4
gpt4 key购买 nike

我想做的是使用 System.Threading.Timer 执行一个有间隔的方法。我的示例代码类似于这个 atm。

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 方法吗?真正发生的是当我运行我的应用程序时执行 WriteSomething 并在 10 秒后应用程序关闭。我想我误解了它是如何工作的,谁能告诉我如何使用 System.Threading.Timer 做到这一点。

在此先感谢,非常欢迎代码示例

最佳答案

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

要实用。将其设置为 100 毫秒,这样您就不会在等待崩溃时长 mustache 。并且不要使用异步计时器来更新 UI,这是没有用的。

关于c# - 在 winForm C# 中使用 System.Threading.Timer 间隔触发方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5607164/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com