Saturday, February 23, 2013

Threading: 02- Thread with parameter

We can pass one argument to thread during thread start

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start("Good Morning");  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object message) {
        Console.WriteLine("Hi, {0}!", message);
    }
}

 

  • Constructor of Thread class here, receives the method to be invoked using a delegate called ParameterizedThreadStart which is defined in BCL.
  • Signature of the parameterized thread start is defined in BCL as

public delegate void ParameterizedThreadStart(object obj);

  • During thread start we can pass value to the Thread

Output

Main Started
Main Completed

Hi, Good Morning!

 

No comments:

Post a Comment