标签:
首先不管是C#也好,还是java也好,对于已经Abort的线程是无法再次Start的,除非是声明私有变量new一个新的线程,网上也有很多人说可以Suspend挂起线程,然后再Resume继续,但是相信聪明的你们早就发现了,微软官方已经将这两个方法设为过时了,不推荐这么用,现在本人就分享一个本人觉得还算比较好用的方法:
private List<Thread> _threadList = new List<Thread>(); //记录产生的线程,可声明为全局公共变量 public Form1() { InitializeComponent(); } private void DoWork() { for (int i = 0; i < 4; i++) { if (i == 0) { Thread t = new Thread(() => { while (true) { BeginInvoke(new Action(() => { label1.Text = DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss"); })); Thread.Sleep(10); } }); _threadList.Add(t); t.Start(); } else if (i == 1) { Thread t = new Thread(() => { while (true) { BeginInvoke(new Action(() => { label2.Text = DateTime.Now.AddDays(1).ToString( "yyyy-MM-dd HH:mm:ss"); })); Thread.Sleep(10); } }); _threadList.Add(t); t.Start(); } else if (i ==2) { Thread t = new Thread(() => { while (true) { BeginInvoke(new Action(() => { label3.Text = DateTime.Now.AddMonths(1).ToString( "yyyy-MM-dd HH:mm:ss"); })); Thread.Sleep(10); } }); _threadList.Add(t); t.Start(); } else if (i == 3) { Thread t = new Thread(() => { while (true) { BeginInvoke(new Action(() => { label4.Text = DateTime.Now.AddYears(1).ToString( "yyyy-MM-dd HH:mm:ss"); })); Thread.Sleep(10); } }); _threadList.Add(t); t.Start(); } } } private void BtnStartClick(object sender, EventArgs e) { Thread _threadMain = new Thread(DoWork); _threadMain.IsBackground = true; _threadList.Add(_threadMain); _threadMain.Start(); } private void BtnStopClick(object sender, EventArgs e) { foreach (var t in _threadList) { t.Abort(); } _threadList.Clear(); }
以上的代码很简单,界面上两个按钮,4个Lable分别显示4个时间,点击开始按钮,开启4个线程,并把4个线程对象加到List集合中,点击结束按钮,将List中的4个线程对象全都Abort,并将List清空,如果想要重启的效果,则可以先调用Stop,然后再调Start即可,是不是很简单吖
标签:
原文地址:http://www.cnblogs.com/guyun/p/4250345.html