关于C#中的线程重启的问题

时间:2023-03-10 07:25:13
关于C#中的线程重启的问题

首先不管是C#也好,还是java也好,对于已经Abort的线程是无法再次Start的,除非是声明私有变量new一个新的线程,网上也有很多人说可以Suspend挂起线程,然后再Resume继续,但是相信聪明的你们早就发现了,微软官方已经将这两个方法设为过时了,不推荐这么用,现在本人就分享一个本人觉得还算比较好用的方法:

     private List<Thread> _threadList = new List<Thread>();   //记录产生的线程,可声明为全局公共变量 

        public Form1()
{
InitializeComponent();
} private void DoWork()
{
for (int i = ; i < ; i++)
{
if (i == )
{
Thread t = new Thread(() =>
{
while (true)
{
BeginInvoke(new Action(() =>
{
label1.Text =
DateTime.Now.ToString(
"yyyy-MM-dd HH:mm:ss");
}));
Thread.Sleep();
}
});
_threadList.Add(t);
t.Start();
}
else if (i == )
{
Thread t = new Thread(() =>
{
while (true)
{
BeginInvoke(new Action(() =>
{
label2.Text =
DateTime.Now.AddDays().ToString(
"yyyy-MM-dd HH:mm:ss");
}));
Thread.Sleep();
}
});
_threadList.Add(t);
t.Start();
}
else if (i ==)
{
Thread t = new Thread(() =>
{
while (true)
{
BeginInvoke(new Action(() =>
{
label3.Text =
DateTime.Now.AddMonths().ToString(
"yyyy-MM-dd HH:mm:ss");
}));
Thread.Sleep();
}
});
_threadList.Add(t);
t.Start();
}
else if (i == )
{
Thread t = new Thread(() =>
{
while (true)
{
BeginInvoke(new Action(() =>
{
label4.Text =
DateTime.Now.AddYears().ToString(
"yyyy-MM-dd HH:mm:ss");
}));
Thread.Sleep();
}
});
_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即可,是不是很简单吖