Create New Thread C#
How to create a new thread in NET. First, create an object ThreadStart delegate. This delegate points to a method that executed by the new thread. Now your need to pass this delegate as a parameter when creating a new Thread instance, You should also call the Thread.Start method to run your process the background.
All examples assume the following namespaces are imported:
1 2 |
using System; using System.Threading; |
DataTables warning (table id = ‘dataTable’): Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy.
1 2 |
Thread t = new Thread (WriteY); // Kick off a new thread t.Start(); // running WriteY() |
The WorkThreadFunction could be defined as follows
1 2 3 4 |
static void WriteY() { for (int i = 0; i < 1000; i++) Console.Write ("y"); } |
Introduction and Concepts
C# supports parallel execution of code through multithreading. A thread is an independent execution path, able to run simultaneously with other threads.
A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system (the ?main? thread), and is made multithreaded by creating additional threads. Here?s a simple example and its output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class ThreadTest { static void Main() { Thread t = new Thread (WriteY); // Kick off a new thread t.Start(); // running WriteY() // Simultaneously, do something on the main thread. for (int i = 0; i < 1000; i++) Console.Write ("x"); } static void WriteY() { for (int i = 0; i < 1000; i++) Console.Write ("y"); } } |