When we want to use a Thread in C#, we usually write a method with the code that the Thread must execute, and when we create the Thread object we set its delegate to the method already created:

public void DoSomethingUsefull()
{
	for (int i = 0; i < 100; i++)
	{
		// doing something...
		Thread.Sleep(500);
	}
}

static void Main()
{
	// here we create the thread, passing to it the right delegate
	Thread t = new Thread(DoSomethingUsefull);
	t.Name = "Test Thread";
	t.Start();
}

dual core

To create a Thread, C# offers the opportunity to use anonymous methods. To use an anonymous method, we need to write the Thread’s code inside the code that creates the Thread using the delegate keyword:

static void Main()
{
	// this time we create the thread using an anonymous method declared "on the fly"
	Thread t = new Thread(delegate()
	{
		for (int i = 0; i < 100; i++)
		{
			// doing something...
			Thread.Sleep(500);
		}
	});
	t.Name = "Test Thread";
	t.Start();
}

This time we used an anonymous method, avoiding the declaration of a new method with the Thread’s code.
I think that the use of anonymous methods isn’t a good programming pratice:
Separing the code to execute in the Thread from the remaining code contribute to the clarity and the riusability of the code, but if we need to create a Thread with very few rows of code, anonymous methods can be a relaxing help! :)


Se sei interessato a questo post, potresti anche provare a leggere:

  • No related posts