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

winform 线程挂起无效果
代码如下:
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 pro7
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }
  public Thread t;
  private void Form1_Load(object sender, EventArgs e)
  {
  CheckForIllegalCrossThreadCalls = false;
  t = new Thread(gettime);
  t.Start();
  }
  public void gettime()
  {
  while (true)
  {
  textBox1.Text = DateTime.Now.ToString();
  Thread.Sleep(1000);
  }
  }

  private void button1_Click(object sender, EventArgs e)
  {
  if (t.ThreadState == ThreadState.Running)
  {
  t.Suspend();
  }
  }

  private void button2_Click(object sender, EventArgs e)
  {
  if (t.ThreadState == ThreadState.Suspended || t.ThreadState == ThreadState.SuspendRequested)
  {
  t.Resume();
  }
  }
  }
}

------解决方案--------------------
C# code
using System;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private ManualResetEvent _ManualResetEvent = new ManualResetEvent(true);
        private Boolean _bAbort = false;

        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            Thread t = new Thread(gettime);
            t.Start();
        }

        public void gettime()
        {
            while (!_bAbort)
            {
                textBox1.Text = DateTime.Now.ToString();
                Thread.Sleep(1000);

                _ManualResetEvent.WaitOne();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _ManualResetEvent.Reset();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            _ManualResetEvent.Set();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _bAbort = true;
        }
    }
}