Skip to main content

Posts

Showing posts with the label lambda expression

Lambda expression and threads

If you are working with C# I’m pretty sure that you used a lambda expression (an action, a predicate, a delegate or a function). Basically you can define a block of code inline (function) and execute this code when you need it. For all of you, that already used this features of C# I have a simple question:      Does the lambda expression executes on the same thread or is executing on a different thread? This information can be very important because running code on a different thread can be expensive. Not only this, there are times when we can have content that is static on the thread and not on our current process. The simplest way to check this is to write a simple console application that displays the thread id. class Program { static void Main(string[] args) { DisplayCurrentThreadId(); Action myAction = DisplayCurrentThreadId; myAction.Invoke(); myAction.Invoke(); DisplayCurrentThreadId(); Console.Read...

Delegates from .NET 1.0 to .NET 4.0

Mai mult ca sigur ati folosit delegate. Sunt utili cand trebuie sa specificam un comportament la runtime si nu la compile time. Prin acest mecanism putem sa scapam de mostenire in locurile unde aceasta a fost folosita pentru a definii un comportament specific. Exista mai multe tipuri de delegates definite core-ul de .NET: Predicate Action Func O sa incerc sa descriu pe scurt fiecare tip de delegate: Action reprezinta o actiune care nu returneaza nici un rezultat. Header-ul la metoda ar fi de forma urmatoare void fx(T) Exista mai multe implementari de Action, se pot definii pana la maxim 16 parametrii. In cazul in care avem nevoie de mai mult de 16 parametri, ne putem definii noi propile actiuni, dar nu cred ca este sanatos sa avem o actiune cu 16 parametrii sau mai multi. Predicate reprezinta o conditie care se ruleaza si care returneaza TRUE sau FALSE bool fx(T) Atat Action cat si Predicate apar odata cu .NET 2.0, dar ajung sa fie folosite la adevarata lor valoare abia in .NET 3.5 c...