profile for TheDaveJay at Stack Overflow, Q&A for professional and enthusiast programmers

Monday 15 November 2010

Lambda and Threading C#

I have found a new way to start a thread that used lambda to point to the method that needs to be executed.
Below is a code snippet on how this can be done!

class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(() => { Sum(2, 1); });
            thread.Start();
            Console.Read();
        }
 
        public static void Sum(int a, int b)
        {
            Console.Write(a + b);
        }
    }

What happens here is that when the code is compiled, and anonymous method is created which then points to the Sum method! Give it a go!


2 comments:

  1. Awesomeness, I'll definately use this. Hopefully I wont get super thread happy due to its ease of use...

    ReplyDelete
  2. Whats nice about this, is thats its super easy to add a callback on when the thread has finished. I will write a blog on that too soon!

    ReplyDelete