C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: ThreadStart is created with a constructor that receives a target function name. This target method must not receive any parameters.
Then: The ThreadStart instance is passed as an argument to the Thread constructor.
ConstructorC# program that uses ThreadStart
using System;
using System.Threading;
class Program
{
static void Main()
{
// Create an array of Thread references.
Thread[] array = new Thread[4];
for (int i = 0; i < array.Length; i++)
{
// Start the thread with a ThreadStart.
ThreadStart start = new ThreadStart(Start);
array[i] = new Thread(start);
array[i].Start();
}
// Join all the threads.
for (int i = 0; i < array.Length; i++)
{
array[i].Join();
}
Console.WriteLine("DONE");
}
static void Start()
{
// This method has no formal parameters.
Console.WriteLine("Start()");
}
}
Output
Start()
Start()
Start()
Start()
DONE
Example: We create 4 ParameterizedThreadStarts, then start and join 4 threads. Start() is executed 4 different times on separate threads.
Tip: With ParameterizedThreadStart, you pass a function name as the argument. This is an object type that you can later cast.
Info: The threads were called in a non-sequential order. There is a pause before the runtime can receive a thread.
Note: You can't count on the order of execution exactly here. A thread may take longer for reasons beyond your control.
C# program that uses ParameterizedThreadStart
using System;
using System.Threading;
class Program
{
static void Main()
{
// Create an array of Thread references.
Thread[] array = new Thread[4];
for (int i = 0; i < array.Length; i++)
{
// Start the thread with a ParameterizedThreadStart.
ParameterizedThreadStart start = new ParameterizedThreadStart(Start);
array[i] = new Thread(start);
array[i].Start(i);
}
// Join all the threads.
for (int i = 0; i < array.Length; i++)
{
array[i].Join();
}
Console.WriteLine("DONE");
}
static void Start(object info)
{
// This receives the value passed into the Thread.Start method.
int value = (int)info;
Console.WriteLine(value);
}
}
Output
1
0
2
3
DONE
Instead: You can use the ThreadStart type, which (fortunately) is detailed also on this page.