using System; using System.Threading; public class MyThread { private int count; private Thread thread; public MyThread() { count = 0; thread = new Thread(Run); thread.Start(); } public void Run() { while(true) { Console.WriteLine("Count: " + count); count++; Thread.Sleep(1000); } } } public class Example { public static void Main() { MyThread thread = new MyThread(); Thread.Sleep(5000); thread.Stop(); } }
using System; using System.Threading.Tasks; public class Example { public static void Main() { Task.Run(() => Console.WriteLine("Hello from Task!")); } }In this example, we use the static Run method provided by the Task class to create and run a new task. This method takes a lambda expression as its argument that represents the code to be executed on the new thread. Package/Library: System.Threading.Tasks