Multi-threaded Way with parameters
#region to perform multithreading with one parameter
Thread mythread = new Thread (new Parameterizedthreadstart (Calculate));
Mythread. IsBackground = true;
Mythread. Start (500);
#endregion
private void Calculate (object Max)//delegate function with one parameter
{
int max = (int) max;
Stopwatch Stopwatch = Stopwatch.startnew ();
for (int i = 0; i < max; i++)
{
Thread.Sleep (5);
}
Stopwatch. Stop ();
Long lsearchtime = stopwatch. Elapsedmilliseconds;
MessageBox.Show (lsearchtime.tostring () + "MS");
}
Method One: Define a class, set the parameters to be passed to the properties of the class, and then assign the parameter value to the class's properties, the class as a parameter to communicate, the following code through two parameter examples, the same as several parameters, the code is as follows
Class MyClass
{
public int Max {get; set;}
public int Min {get; set;}
}
#region The first way: Execute multithreading with multiple parameters
MyClass model = new MyClass ();
Model. Max = 500;
Model. Min = 0;
Thread mythread1 = new Thread (new Parameterizedthreadstart (Calculatetwo));
Mythread1. IsBackground = true;
Mythread1. Start (model);
#endregion
private void Calculatetwo (object Myclass)//delegate function with multiple arguments
{
MyClass model = (MyClass) MyClass;
Stopwatch Stopwatch = Stopwatch.startnew ();
for (int i = model. Min; I < model. Max; i++)
{
Thread.Sleep (5);
}
Stopwatch. Stop ();
Long lsearchtime = stopwatch. Elapsedmilliseconds;
MessageBox.Show (lsearchtime.tostring () + "MS");
}
Mode two: lambda expression, simple and convenient, the code is as follows:
#region The second way: Execute multithreading with multiple parameters
Thread mythread2 = new Thread (() = Calculatethree (500, 0));
Mythread2. IsBackground = true;
Set to the back line, the program is closed after the process is also closed, if not set true, the program is closed, this line have in the memory, will not be closed
Mythread2. Start ();
#endregion
private void Calculatethree (int max,int Min)//delegate function with multiple arguments
{
Stopwatch Stopwatch = Stopwatch.startnew ();
for (int i = Min; i < Max; i++)
{
Thread.Sleep (5);
}
Stopwatch. Stop ();
Long lsearchtime = stopwatch. Elapsedmilliseconds;
MessageBox.Show (lsearchtime.tostring () + "MS");
}
How to write multi-threaded with parameters?