Home > Software engineering >  Difference in initialization of Threads .NET
Difference in initialization of Threads .NET

Time:01-10

What's the difference between following initializations of the threads and when I should use them?

Printer printer = new Printer();
Thread thread = new Thread(new ThreadStart(printer.Print0));
Thread thread2 = new Thread(printer.Print0);
Thread thread3 = new Thread(() => printer.Print0());

CodePudding user response:

The class System.Threading.Thread has the constructors :

public class Thread
{
    public Thread (System.Threading.ThreadStart start);
}

Why System.Threading.ThreadStart start is a delegate :

public delegate void ThreadStart();

The syntax to instantiate a delegate is :

ThreadStart myDelegate = new ThreadStart(printer.Print0);

// C#2 add this sugar syntax, but it's same instruction that below
ThreadStart myDelegate = printer.Print0;

Then this syntax are equivalent :

Thread thread = new Thread(new ThreadStart(printer.Print0));
Thread thread2 = new Thread(printer.Print0);

Just the second use the sugar syntax add in C#2.


In C#3, lambda is add in the language with a new way to declare a delegate :

ThreadStart myDelegate = () => { printer.Print0 };

It's like :

public class MyLambda
{
    public Printer printer;

    void Run()
    {
        printer.Print0();
    }
}

ThreadStart myDelegate = new MyLambda() { printer = printer }.Run;

Not exactly like the first example, because technically it call a intermediate method. But the only perceptive difference is the call stack... I consider this syntax similar.


To your question from your comment :

Is there any advantage to use the explicit call and the lambda expression?

No, it's just different syntax. You can choose the one you prefer whitout other consideration.

  • Related