我想要做的是使用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";
}
}
Run Code Online (Sandbox Code Playgroud)
}
这个推测不是每10秒执行一次WriteSomething方法.发生的事情是WriteSomething在我运行应用程序时执行,10秒后应用程序关闭.想想我已经误解了它是如何工作的,任何人都可以通过System.Threading.Timer告诉我如何做到这一点.
在此先感谢,代码示例非常受欢迎
更可能的情况是它在10秒后崩溃.您无法触及回调中的任何控件,它在错误的线程上运行.您必须使用Control.BeginInvoke().这使得使用System.Threading.Timer而不是System.Windows.Forms.Timer 完全没有意义.
务实.让它达到100毫秒,这样你就不会长胡子等待崩溃.并且不要使用异步计时器来更新UI,这是没用的.