Tuesday, 21 August 2018

C#: Pass parameters to a method executed by thread

By using lambda expression, you can pass arguments to the method that is executed by the thread.

Program.cs
using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(() => print("uploadTask"));

            t1.Name = "Thread1";

            t1.Start();
        }

        public static void print(String task)
        {
            Console.WriteLine("{0} Executing the task {1}", Thread.CurrentThread.Name, task);
        }
    }
}

Output
Thread1 Executing the task uploadTask

By using lambda expressions, you can even execute a block of statements.

Example
            Thread t1 = new Thread(() => {
                Console.WriteLine("Hello World");
                Console.WriteLine("Executing second statement");
            });

Program.cs

using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(() => {
                Console.WriteLine("Hello World");
                Console.WriteLine("Executing second statement");
            });

            t1.Name = "Thread1";

            t1.Start();
        }
    }
}

Output
Hello World
Executing second statement

By passing the arguments to Thread Start method, you can pass the arguments to the method that is executed by the thread.


Program.cs

using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main()
        {
            Thread t = new Thread(Print);
            t.Start("Hello World");
        }

        static void Print(object message)
        {
            Console.WriteLine(message);
        }
    }
}

Output
Hello World

Note
There is a limitation in passing the arguments to a method using ThreadStart, it accepts only one argument.


Previous                                                 Next                                                 Home

No comments:

Post a Comment