when I click button1 should print A s but when I click button2 need to stop thread1 and need to start thread2, what is the wrong in here please help me
private void button1_Click(object sender, EventArgs e)
{
if (thread2.IsAlive)
{
thread2.Suspend();
}
thread1 = new Thread(threadOne);
thread1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
if (thread1.IsAlive)
{
thread1.Suspend();
}
thread2 = new Thread(threadTwo);
thread2.Start();
}
private void threadOne() {
for (int i=0; i < 20; i++ )
{
Console.Write("A");
Thread.Sleep(500);
}
}
private void threadTwo()
{
for (int i = 0; i < 20; i++)
{
Console.Write("B");
Thread.Sleep(500);
}
}
There’s quite a lot wrong, as the other posters have correctly pointed out. I would add this:
1) Most threads in commercial-grade software never terminate during the lifetime of the application – they are written as infinite loops with blocking calls that wait for some sort of signaling from other threads or I/O operations.
2) Continual create/terminate/destroy of thread objects is expensive, difficult to control, awkward-to-debug, unreliable and generally causes pain.
3) If your multithread code contains any of the following:
You should probably think again 🙂
I know you’re only learning, but sometimes it’s better to patch up holes before they get any bigger 🙂