ThreadStart:
The ThreadStart delegate is defined as void ThreadStart(), which means that the method executed cannot have parameters. ThreadStart threadStart=new ThreadStart(Calculate); Thread thread=new Thread(threadStart); thread. Start(); public void Calculate() { double Diameter=0.5; Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI); } Here we use a delegate that defines a ThreadStart type, which defines the method that the thread needs to execute: Calculate, in which the circumference of a circle with a diameter of 0.5 is calculated, and outputs. This constitutes the simplest example of multithreading, which in many cases is sufficient
ParameterThreadStart: ParameterThreadStart is defined as void ParameterizedThreadStart(object state), and the startup function of the thread defined using this delegate can accept an input parameter, for example:
ParameterizedThreadStart threadStart=new ParameterizedThreadStart(Calculate) Thread thread=new Thread() ; thread. Start(0.9); public void Calculate(object arg)
{ double Diameter=double(arg); Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI);
}
The Calculate method has a parameter of type object, although there is only one parameter, and it is also an object type, and it still needs to be converted when using it, but fortunately, there can be parameters, and by combining multiple parameters into a class, and then passing the instance of this class as a parameter, you can achieve multiple parameter transfer. Like what:
class AddParams
{ public int a, b;
public AddParams(int numb1, int numb2) { a = numb1; b = numb2; }
} #endregion
class Program
{ static void Main(string[] args) { Console.WriteLine("***** Adding with Thread objects *****"); Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.ManagedThreadId);
AddParams ap = new AddParams(10, 10); Thread t = new Thread(new ParameterizedThreadStart(Add)); t.Start(ap); Console.ReadLine(); }
#region Add method static void Add(object data) { if (data is AddParams) { Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.ManagedThreadId);
AddParams ap = (AddParams)data; Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b); } } #endregion
}
} |