1. Asynchronous delegation to start thread
public class Program { public static void Main(string[] args) { Action<int, int> a = add; (3, 4, null, null); ("Execution thread"); (); } static void add(int a, int b) { (a + b); } }
2. Open thread through Thread class
public class Program { public static void Main(string[] args) { Thread t1; Thread t2; t1 = new Thread(SetInfo1); t2 = new Thread(SetInfo2); (); //Thread sleep //(1000); //Suspend thread (); //Continue to execute the thread (); //End thread //(); (); (); } //Odd thread public static void SetInfo1() { for (int i = 0; i < 100; i++) { if (i % 2 != 0) { ("Odd number" + i); } } } //Even thread public static void SetInfo2() { for (int i = 0; i < 100; i++) { if (i % 2 == 0) { ("Even number is" + i); } } } }
3. Open threads through thread pool
//Thread pool can be regarded as a container for threads; an application can only have one thread pool at most; ThreadPool static class uses the QueueUserWorkItem() method to rank work functions into the thread pool; each time a work function is placed, it is equivalent to requesting to create a thread; //The function of thread pool: //1. The thread pool is designed for threads that suddenly burst out in large numbers. Through a limited number of fixed threads, the time required to create and destroy threads is reduced, thereby improving efficiency. //2. If a thread has a very long time, there is no need to use a thread pool (not that it cannot be used for a long time, but it is not suitable.), and we cannot control the start, suspend, and abort of threads in the thread pool. Moreover, we cannot control the start, suspend, and abort of threads in the thread pool. public class Program { public static void Main(string[] args) { (new WaitCallback(TestThreadPool), new string[] { "hjh" }); (); } public static void TestThreadPool(object state) { string[] arry = state as string[];//The value of the parameter passed int workerThreads = 0; int CompletionPortThreads = 0; (out workerThreads, out CompletionPortThreads); (() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads); } }
4. Start threading through task Task
public class Program { public static void Main(string[] args) { Task task = new Task(DownLoadFile_My); (); (); } static void DownLoadFile_My() { ("Start download...thread ID:"+); (500); ("Download is complete!"); } }
The above is the detailed content of the four methods of starting thread in C#. For more information about starting thread in C#, please pay attention to my other related articles!