TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# ThreadStart Use

This C# example program uses ThreadStart when making new threads.

ThreadStart specifies a target method.

It does not support any arguments to the method. We use the ThreadStart type. We create an instance of it and pass that to the Thread constructor.

Example. First, this example C# program creates an array of four different threads. It starts a parameterless method on each thread. It then joins the threads together in a sequential order.

Next, we see that ThreadStart is created with a constructor that receives a function name as its only argument: the target method. This target method must not receive any formal parameters.

Then: The ThreadStart instance is passed as an argument to the Thread constructor.

Constructor

C# 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

Discussion. Using this same general example, we explain the Join method in more detail, also on this site. Please visit the appropriate article for a more thorough explanation of the Join method on the Thread type in the C# language.

Thread Join Method

Summary. The ThreadStart type enables you to start a thread and pass no arguments to the target method. For parameterless target methods, this type is ideal, and you should pass it to the Thread constructor.

Tip: For more detailed information on threading in the C# language and .NET Framework, check out the thread category on this site.

ParameterizedThreadStart


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf