C# Threads using anonymous methods
Categories: C
Tags:
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!
Se sei interessato a questo post, potresti anche provare a leggere:
- No related posts
18 Sep 2007 dzamir
Одежда секонд хэнд самых популярные марок: Difference, Ralf Lauren, Dusty Armada, Calvin Klein, Tommy Hilfiger в Санкт-Петербурге.
По вопросам поставки секонд хэнд в Санкт-Петербурге обращайтесь по следующим адресам и телефонам:
Адрес: Санкт-Петербург, ул. Басейная 14 оф 101
UsandoТелефоны: (812) 930-56-38, +7 963 341400, +7 921 5701888
Скачать бесплатно тут KIS KEY
UsandoТы считаешь, что у тебя колоссально необычные сексуальные желания? Подружка называет тебя извращенцем? Она нисколько не понимает! А здесь тебя поймут, потому что здесь, в сообществе сторонников свободного и дикого секса считается, что любые желания достойны уважения и воплощения! Освободи свою сексуальную фантазию от моральных устоев и наслаждайся жизнью!
Usando