Click here to Skip to main content
15,895,962 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is a multi thread simple console program , i want to start one thread on pressing the character "t" and close it on pressing the character "x". the following is the code but when i press "t" for the first time its started and close on pressing "x" as well but when i tried to press "t" for the second time its stuck.

using System;
using System.Threading;
namespace consoleApp2
{
    class ThreadTest
    {
        static void Main()
        {
            Thread t1 = new Thread(staric); //  this is staric in a positin e
            Thread t2 = new Thread(staric2); // this is staric 2 in diffrent position
            while (true)
            {
                char x = Console.ReadKey().KeyChar;
                int Time = 1;
                if (x == 't' && Time == 1)
                {
                    Time++;
                    t1.Start();
                }
                else if (x == 't' && Time > 1)
                {
                    Time++;
                    t2.Start();
                }
                if (x == 'x' && Time == 1)
                {
                    Time++;
                    t1.Suspend();
                }
                else if (x == 'x' && Time == 2)
                {
                    Time++;
                    t2.Suspend();
                }
            }
        }
        static void staric()
        {
            while (true)
            {
                Console.SetWindowPosition(0, 0);
                Console.Write("-");
                Thread.Sleep(70);
                Console.Clear();
                Console.Write("\\");
                Thread.Sleep(70);
                Console.Clear();
                Console.Write("|");
                Thread.Sleep(70);
                Console.Clear();
                Console.Write("/");
                Thread.Sleep(70);
                Console.Clear();
            }
        }
        static void staric2()
        {
            while (true)
            {
                Console.SetWindowPosition(0, 1);
                Console.Write("s");
            }
        }
    }
}
Posted

Use t1.Join, t2.Join rather then Suspend.

When you you tell Join, it blocks everything until the thread is done.

Good luck
 
Share this answer
 
Your logic is wrong (Time is set to 1 at every while cycle).
:)
 
Share this answer
 
Comments
arslan3488 10-Nov-10 9:32am    
so what can i do then

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900