create a thread in csharp

To create a new thread in C#, you can use the Thread class defined in the System.Threading namespace. Here's an example:

main.cs
using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        // create a new thread and start it
        Thread t = new Thread(new ThreadStart(DoWork));
        t.Start();
        
        // wait for the thread to finish
        t.Join();
        Console.WriteLine("Thread finished");
    }
    
    static void DoWork() {
        Console.WriteLine("Thread started");
        
        // do some work here...
        
        Console.WriteLine("Thread finished");
    }
}
513 chars
23 lines

In this example, we create a new thread and start it by calling its Start() method. The ThreadStart delegate passed to the thread constructor specifies the method that will be executed on the new thread.

We also use the Join() method to wait for the thread to finish before continuing execution on the main thread. This ensures that any work done by the new thread is completed before the program terminates.

Note that working with threads can be complex and error-prone. You should be familiar with multithreading concepts like concurrency and parallelism, as well as techniques for synchronization and communication between threads, before implementing them in your programs.

gistlibby LogSnag