日期:2014-05-17  浏览次数:20869 次

线程与timer
用button可以让timer立即停止再立即开始
  private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            timer1.Enabled = true;
        }
但是用线程却只能停止timer停止不能再开始
  private void button4_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(thd));
            th.Start();
        }
        private void thd()
        {
            while (true)
            {
                timer1.Enabled = false;
                timer1.Enabled = true;
                Thread.Sleep(100);
            }
        }

能说说是为什么吗???

------解决方案--------------------
由于Timer是主线程创建的,只要把Timer在线程里创建就可以了,附上代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int a = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(thd));
            th.Start();
        }
        private void thd()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 100;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
            timer.Enabled = t