Threading in C# with a Console Application
-
Hello. I'm new to C# (switched from Java) and I am trying to see if there is a way to keep a thread running indefinitely, with no timeout. I have a console application written, but I need it to run more like a windows service in that I want all threads to run until they are told to stop. Is there a special class that will help with this, or does anyone know of a good resource that I can learn more about this specifically??
-
Hello. I'm new to C# (switched from Java) and I am trying to see if there is a way to keep a thread running indefinitely, with no timeout. I have a console application written, but I need it to run more like a windows service in that I want all threads to run until they are told to stop. Is there a special class that will help with this, or does anyone know of a good resource that I can learn more about this specifically??
You can use the namespace System.Threading for this. The same as you use threading in java, you can use it in C#.
class ThreadTest
{
static void Main()
{
Thread t = new Thread (WriteY);
t.Start(); // Run WriteY on the new thread
while (true) Console.Write ("x"); // Write 'x' forever }static void WriteY()
{
while (true) Console.Write ("y"); // Write 'y' forever
}
}To stop the thread, use t.Stop(); Or you can sleep inside the thread with Thread.Sleep(1000);//one second Good luck
-
You can use the namespace System.Threading for this. The same as you use threading in java, you can use it in C#.
class ThreadTest
{
static void Main()
{
Thread t = new Thread (WriteY);
t.Start(); // Run WriteY on the new thread
while (true) Console.Write ("x"); // Write 'x' forever }static void WriteY()
{
while (true) Console.Write ("y"); // Write 'y' forever
}
}To stop the thread, use t.Stop(); Or you can sleep inside the thread with Thread.Sleep(1000);//one second Good luck
Thanks SO much... I don't know why it didn't dawn on me to use a while(true) statement... silly me! But thank you, that helps a lot!!
-
Thanks SO much... I don't know why it didn't dawn on me to use a while(true) statement... silly me! But thank you, that helps a lot!!
A better way to wait is to use the Thread.Join[^] method. That way 1. You don't need additional logic to have the main method break out of the loop when the thread(s) exit. 2. Infinite looping uses CPU cycles, whereas Join tells the OS scheduler to not schedule the current thread until the thread passed as the parameter completes.
Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro