[C#] Create New Thread Sharp

Create-New-Thread-Sharp

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:

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.

 Thread t = new Thread (WriteY);          // Kick off a new thread
    t.Start();                               // running WriteY()
    

The WorkThreadFunction could be defined as follows

   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:

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");
  }
}
5/5 - (1 vote)