加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在WinForm C#中使用System.Threading.Timer进行间隔的射击方法

发布时间:2020-12-15 23:58:27 所属栏目:百科 来源:网络整理
导读:我想要做的是使用System.Threading.Timer执行一个间隔的方法. 我的示例代码看起来像这个atm. public partial class Form1 : Form{ public Form1() { InitializeComponent(); System.Threading.Timer t1 = new System.Threading.Timer(WriteSomething,null,Ti
我想要做的是使用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毫秒,这样你就不会长胡子等待崩溃.并且不要使用异步计时器来更新UI,这是没用的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读