Saturday, February 23, 2013

Threading: 03- Thread with multiple parameters

Thread class supports two types of methods

  • Method without parameter and return values- using ThreadStart delegate
  • Method with one object type parameter and without return values- using ParameterizedThreadStart delegate

To pass multiple values to Thread, we can create a small class to store multiple parameters and send it as the parameter

 

Example:

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(new GreetInfo() { Name = "Bob", Message = "Good Morning" });  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private class GreetInfo {
        public string Name { get; set; }
        public string Message { get; set; }
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as GreetInfo).Name, (info as GreetInfo).Message);
    }
}

No comments:

Post a Comment