[英]My Timer won't tick c#
我的計時器不會計時,我嘗試打印以檢查計時器是否已啟動,已啟動但從未計時。 這是代碼:
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
timer = new Timer();
timer.Enabled = true;
timer.Interval = 50;
timer.Tick += new EventHandler(timer_Tick);
//Console.WriteLine("STARTING TIMER");
timer.Start();
NewFile();
}
private void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("TIMER TICKS");
doc.MoveBalls(leftX, topY, width, height);
doc.CheckCollision();
Invalidate(true);
Console.WriteLine("Moving2");
}
在附加OnTick
事件之前,您已啟用計時器。 將Enabled
設置為true基本上與timer.Start()
相同。 刪除已啟用的分配,或用它替換Start()調用。
除了上面給出的答案外,您還可以使用Timer線程,該線程接受回調和一個狀態對象,以確保您的工作線程安全,如下所示
在名稱空間之前包含庫之后
using System.Threading;
//您的名稱空間
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
private Timer _timer = new Timer(CallBakFunction, null, _updateInterval, _updateInterval);
private void CallBakFunction(object state)
{
}
您可以按照以下步驟進行操作:
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
private Timer _timer ;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
_timer = new Timer(timer_Tick, null, _updateInterval, _updateInterval);
NewFile();
}
private void timer_Tick(object state)
{
MessageBox.Show("TIMER TICKS");
doc.MoveBalls(leftX, topY, width, height);
doc.CheckCollision();
Invalidate(true);
Console.WriteLine("Moving2");
}
我已經更新了最終結果視頻,為您提供幫助,請查看以下內容:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(1);
private System.Threading.Timer _timer;
public Form1()
{
InitializeComponent(); this.DoubleBuffered = true;
_timer = new System.Threading.Timer(timer_Tick, null, _updateInterval, _updateInterval);
NewFile();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void NewFile() { }
private void timer_Tick(object state)
{
MessageBox.Show("TIMER TICKS");
//doc.MoveBalls(leftX, topY, width, height);
//doc.CheckCollision();
//Invalidate(true);
Console.WriteLine("Moving2");
}
}
}
使用System.Windows.Forms.Timer
與Winform一起使用
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
System.Windows.Forms.Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 50;
timer.Tick += new EventHandler(timer_Tick);
//Console.WriteLine("STARTING TIMER");
timer.Start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.