因为Thread的Suspend()与Resume()方法都过时了,只能采用其它方法来实现该功能。
创建两个线程,点击停止1线程将线程1停止,开启1线程将线程1开启。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 停止1线程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
foreach (KeyValuePair<int, ThreadInfo> kv in dic)
{
if (kv.Key == 1)
{
kv.Value.mre.Reset();//重置
kv.Value.isStop = true;//把停止线程的标识设置为true
}
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (KeyValuePair<int, ThreadInfo> kv in dic)
{
if (kv.Key == 2)
{
kv.Value.mre.Reset();//重置
kv.Value.isStop = true;//把停止线程的标识设置为true
}
}
}
private void button3_Click(object sender, EventArgs e)
{
foreach (KeyValuePair<int, ThreadInfo> kv in dic)
{
if (kv.Key == 1)
{
kv.Value.mre.Set();//把线程从无信号设置为有信号--开启线程
}
}
}
private void button4_Click(object sender, EventArgs e)
{
foreach (KeyValuePair<int, ThreadInfo> kv in dic)
{
if (kv.Key == 2)
{
kv.Value.mre.Set();//把线程从无信号设置为有信号--开启线程
}
}
}
IDictionary<int, ThreadInfo> dic = new Dictionary<int, ThreadInfo>();
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 2; i++)
{
Thread th = new Thread(new ParameterizedThreadStart(createThread));
ThreadInfo info = new ThreadInfo()
{
Id = i,
isStop = false,
myThread = th,
mre = new ManualResetEvent(false) //初始状态需要设置为false,不然waitone无效
};
info.Start();
dic.Add(i, info);
}
}
private object obj = new object();
void createThread(object info)
{
ThreadInfo thread = (ThreadInfo)info;
while (true)
{
if (thread.isStop) //如果当前对象的标记为true,则把当前的对应设置为waitone(挂起线程)
{
thread.mre.WaitOne();
}
lock (obj)
{
int i = 0;
appendMethod("线程" + thread.Id + "" + i.ToString() + "\r\n");
Thread.Sleep(1000);
}
}
}
delegate void appendDataDelegate(string message);
void appendMethod(string message)
{
if (richTextBox1.InvokeRequired)
{
appendDataDelegate append = new appendDataDelegate(appendMethod);
richTextBox1.BeginInvoke(append, new object[] { message });
}
else
{
richTextBox1.AppendText(message);
}
}
}
/// <summary>
/// 创建线程信息类
/// </summary>
public class ThreadInfo
{
public int Id { get; set; }
public Thread myThread { get; set; }
public ManualResetEvent mre { get; set; }
public bool isStop { get; set; }
public void Start()
{
myThread.Start(this);
}
}