Because the suspend () and resume () Methods of thread are outdated, this function can only be implemented using other methods.
Create two threads, click STOP 1 to stop thread 1, enable thread 1 to enable thread 1.
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
/// <Summary>
/// Stop thread 1
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void button#click (Object sender, eventargs E)
{
Foreach (keyvaluepair <int, threadinfo> kV in DIC)
{
If (Kv. Key = 1)
{
KV. value. Mre. Reset (); // Reset
KV. value. isstop = true; // set the stop thread ID to true.
}
}
}
Private void button2_click (Object sender, eventargs E)
{
Foreach (keyvaluepair <int, threadinfo> kV in DIC)
{
If (Kv. Key = 2)
{
KV. value. Mre. Reset (); // Reset
KV. value. isstop = true; // set the stop thread ID to true.
}
}
}
Private void button3_click (Object sender, eventargs E)
{
Foreach (keyvaluepair <int, threadinfo> kV in DIC)
{
If (Kv. Key = 1)
{
KV. value. Mre. Set (); // set the thread from non-signal to signal-enable the thread
}
}
}
Private void button4_click (Object sender, eventargs E)
{
Foreach (keyvaluepair <int, threadinfo> kV in DIC)
{
If (Kv. Key = 2)
{
KV. value. Mre. Set (); // set the thread from non-signal to signal-enable the thread
}
}
}
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) // you must set the initial status to false. Otherwise, waitone is invalid.
};
Info. Start ();
Dic. Add (I, Info );
}
}
Private object OBJ = new object ();
Void createthread (Object info)
{
Threadinfo thread = (threadinfo) Info;
While (true)
{
If (thread. isstop) // if the current object is marked as true, the current corresponding value is set to waitone (thread suspension)
{
Thread. Mre. waitone ();
}
Lock (OBJ)
{
Int I = 0;
Appendmethod ("Thread" + 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>
/// Create a thread Information Class
/// </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 );
}
}