27 Sep 2007

C# Threads using anonymous methods

Via Coders4fun:

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();
}

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!

Tags: , ,
Categories: Visual Studio

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

Gravatar

lory cn

February 21 2008 03:37

Verizon is about the only place you can get the authentic RIM product and matching door. Most other sites are out of stock and even when they are in stock they have the black battery door which looks like crap. http://www.batteryfast.co.uk
I tested this camera for a client. I didn’t have the light running for more than 15 minutes. The battery lasted approximately 6 hours before recharging. The LCD, however, had a few dead pixels - never saw this before. Tried returning for exchange and had to put up quite a fight. Anyone else seen this? http://www.batteryfast.com
:)

Add comment


(Will show your Gravatar icon)  

  Country flag





Live preview

Gravatar

July 6 2008 06:21