-1

I'm trying to understand C# and am very confused by this block of code.

Thread thread = new Thread(new ThreadStart(() =>
{
       Thread.Sleep(_rnd.Next(50, 200));
       //do other stuff
}));
thread.Start();

I know a thread is being created and then started but I don't understand the => syntax in this case. From checking other posts on this site, which were hard to find regarding =>, I think it was to do with delegates or that something is being returned? Can anyone shed some light on this? Thanks.

Murilo Santana
  • 615
  • 1
  • 7
  • 13
lordhans
  • 31
  • 3

1 Answers1

1

Below you'll find some different ways to work with functions and delegates. The all do the same thing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SO39543690
{
  class Program
  {
    static Random _rnd = new Random();

    static void Proc()
    {
      Console.WriteLine("3. Processing...");
      Thread.Sleep(_rnd.Next(50, 200));
    }

    static void Main(string[] args)
    {
      Thread thread = new Thread(new ThreadStart(() =>
      {
        Console.WriteLine("1. Processing...");
        Thread.Sleep(_rnd.Next(50, 200));
      }));
      thread.Start();

      thread = new Thread(() =>
      {
        Console.WriteLine("2. Processing...");
        Thread.Sleep(_rnd.Next(50, 200));
      });
      thread.Start();

      thread = new Thread(Proc);
      thread.Start();

      thread = new Thread(delegate ()
      {
        Console.WriteLine("4. Processing...");
        Thread.Sleep(_rnd.Next(50, 200));
      });
      thread.Start();

      Action proc = () =>
      {
        Console.WriteLine("5. Processing...");
        Thread.Sleep(_rnd.Next(50, 200));
      };
      thread = new Thread(new ThreadStart(proc));
      thread.Start();


      Console.WriteLine("END");
      Console.ReadLine();
    }
  }
}