C #: Can't I use an anonymous delegate in ThreadStart?

Could I have an anonymous delegate declaration something similar to the following:

    ThreadStart starter = delegate() { go(); };
            ...

    static void go()
    {
      Console.WriteLine("Nice Work");
    }

   // (or)

   ThreadStart starter=delegate() { Console.WriteLine("Hello");}
+3
source share
3 answers

What error are you getting? Missing semicolon? This compiles for me.

    static void go()
    {
        Console.WriteLine("Nice Work");
    }

    public void Run()
    {
        ThreadStart starter1 = delegate() { go(); };

        ThreadStart starter2 = delegate() { Console.WriteLine("Hello");};

        ThreadStart starter3 = () =>  Console.WriteLine("Hello");

    }
+3
source

You can skip ThreadStart. That should work.

Thread t = new Thread(() => 
{
  Console.WriteLine("Hello!");
});
+7
source

Yes, you can. What's the question?

By the way, you are missing a semicolon at the end of the second example:

ThreadStart starter=delegate() { Console.WriteLine("Hello");}

it should be:

ThreadStart starter = delegate { Console.WriteLine("Hello"); };

Although the span that I added is a personal choice.

+1
source

Source: https://habr.com/ru/post/1719911/


All Articles