C # Passing parameters by thread,
There are two methods for passing parameters:
1. Create a class parameter passing method with Parameters
2. Use Thread. start (8) to directly pass the parameter. This method will receive an object and pass the object to the Thread.
A single parameter of the object type must be received.
3. Use the lambda expression to pass parameters through the closure.
3.1 When lambda expressions use any local variable, C # automatically generates a class and uses the variable as an attribute of the class. In fact, it is basically the same as the first method, but we do not need to define the class. C # will automatically compile and implement the class.
3.2 using lambda expressions may cause some problems. For example, using the same variable in multiple lambda expressions will share the variable value.
using System;using System.Threading;namespace testThread_Transferparameters{ class Program { static void Main(string[] args) { //1 var sample = new ThreadSample(10); var threadone = new Thread(sample.CountNumbers); threadone.Name = "ThreadOne"; threadone.Start(); threadone.Join(); Console.WriteLine("------------------"); //2 var threadtwo = new Thread(count); threadtwo.Name = "threadtwo"; threadtwo.Start(8); threadtwo.Join(); Console.WriteLine("------------------"); //3 var threadthree = new Thread(() => CountNumbers(20)); threadthree.Name = "threadthree"; threadthree.Start(); threadthree.Join(); Console.WriteLine("------------------"); int i = 10; var threadfour = new Thread(() => PrintNumber(i)); i = 20; var threadfive = new Thread(() => PrintNumber(i)); threadfour.Start(); threadfive.Start(); } static void count(object iterations) { CountNumbers((int)iterations); } static void CountNumbers(int iterations) { for (int i = 1; i <= iterations; i++) { Thread.Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i); } } static void PrintNumber(int number) { Console.WriteLine(number); } } class ThreadSample { private readonly int _iterations; public ThreadSample(int iterations) { _iterations = iterations; } public void CountNumbers() { for (int i = 1; i <= _iterations; i++) { Thread.Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i); } } }}
The result is as follows: