//为什么用线程调用timer时,timer不执行
//调用另外哪个timer会执行吗?
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
namespace MyThread
{
public class TestThread
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Timer timer1;
private System.Threading.Thread timeThread;
public TestThread()
{
timer1.Tick += new System.EventHandler(this.timer1_Tick);
timer1.Interval = 100;
}
private void StartTime()
{
//开始timer,但是没有反应
timer1.Start();
}
private void RunThread()
{
//这里开始线程
timeThread = new Thread(new ThreadStart(StartTime));
timeThread.Start();
}
private void timer1_Tick(object sender, System.EventArgs e)
{
this.label1.Text = DateTime.Now.ToString();
}
}
}
先看看timer有没有设置为可用
System.Windows.Forms.Timer is a forms-based timer,It runs entirely on the UI thread.
So I think you should use System.Timers.Timer or System.Threading.Timer.
同意楼上,加上这句就可以了
this.timer1.Enabled = true;
using System;
using System.Threading;
class TimerExampleState
{
public int counter = 0;
public Timer tmr;
}
class App
{
public static void Main()
{
TimerExampleState s = new TimerExampleState();
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
// Create a timer that waits one second, then invokes every second.
Timer timer = new Timer(timerDelegate, s,1000, 1000);
// Keep a handle to the timer, so it can be disposed.
s.tmr = timer;
// The main thread does nothing until the timer is disposed.
while(s.tmr != null)
Thread.Sleep(0);
Console.WriteLine("Timer example done.");
}
// The following method is called by the timers delegate.
static void CheckStatus(Object state)
{
TimerExampleState s =(TimerExampleState)state;
s.counter++;
Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
if(s.counter == 5)
{
// Shorten the period. Wait 10 seconds to restart the timer.
(s.tmr).Change(10000,100);
Console.WriteLine("changed...");
}
if(s.counter == 10)
{
Console.WriteLine("disposing of timer...");
s.tmr.Dispose();
s.tmr = null;
}
}
}
try:
namespace MyThread
{
public class TestThread
{
private bool _falg = false;
private System.Windows.Forms.Label label1;
private System.Threading.Thread timeThread;
public TestThread()
{
}
private void RunThread()
{
//这里开始线程
this._flag = true;
timeThread = new Thread(new ThreadStart(TestThreadTimer));
timeThread.Start();
}
private void StopThread()
{
this._flag = false;
if(timeThread.ThreadState != ThreadState.Running)
timeThread.Start();
timeThread.Abort();
}
public void TestThreadTimer()
{
while(this._flag)
{
this.label1.Text = DateTime.Now.ToString();
System.Threading.Thread.Sleep(500);
}
}
}
}