infinite thread c# in csharp

To create an infinite thread in C#, you can use an infinite loop that runs inside a separate thread. Here is an example:

main.cs
using System.Threading;
using System;

public class Program
{
    public static void Main()
    {
        // create the thread
        Thread infiniteThread = new Thread(InfiniteLoop);
        // start the thread
        infiniteThread.Start();
        // do something else on the main thread
        Console.WriteLine("Main thread is running");
    }

    // infinite loop that runs on a separate thread
    private static void InfiniteLoop()
    {
        while (true)
        {
            Console.WriteLine("Infinite thread is running");
            // add a delay to prevent the loop from consuming too much CPU
            Thread.Sleep(1000);
        }
    }
}
667 chars
27 lines

In this example, the Main method creates a new thread and starts it. The thread runs the InfiniteLoop method, which contains an infinite loop that writes a message to the console and then waits for 1 second before starting again. This delay prevents the loop from consuming too much CPU.

When you run this program, you will see the messages from the infinite loop printed to the console repeatedly, while the main thread continues to execute other code.

gistlibby LogSnag