Showing posts with label Delegates. Show all posts
Showing posts with label Delegates. Show all posts

Tuesday, October 7, 2014

Set a Property Value from an Expression in .NET

In .NET both Action and Func classes are actually delegates that can be invoked to execute code, whereas the Expression class represents an expression tree that can potentially be compiled into executable code at run time. Expressions are particularly fun because they are malleable, and you can use them dynamically create delegates.

For example, you can create a generic statement that allows you to assign values to properties. This means that one piece of code can use a lambda to select a property for assignment, and another unrelated piece of code can use that expression to dynamically assign the value.

Thanks to AnxiousdeV for coming up with this solution on Stack Overflow.

Test

public class ExpressionTests
{
    public int X { get; set; }
 
    [Fact]
    public void GetSetPropertyAction()
    {
        // Create an expression.
        var expression = GetExpression<ExpressionTests, int?>(c => c.X);
        // Use our extension method to create the action.
        var assignAction = expression.GetSetPropertyAction();
 
        // Set the property.
        assignAction(this, 2);
        // Assert that the value was set correctly.
        Assert.Equal(2, X);
    }
 
    private static Expression<Func<T, U>> GetExpression<T, U>(
        Expression<Func<T, U>> expression)
    {
        // We are only using this method to create an expression.
        return expression;
    }
}

Saturday, June 21, 2014

Waiting for Events with Tasks in .NET

Would you like to just await the next time that an event fires? It takes a little setup, but you can!

Migrating your code from using an Event-based Asynchronous Pattern to an Task-based Asynchronous Pattern can be very tricky. You can use the TaskCompletionSource to manage your Task, and then you just need to create the wire up around registering and unregistering your event handler. Unfortunately this process is not nearly as generic as I would like.

Event-based Asynchronous Pattern Tests

Here is a way of waiting for an event to fire by simply sleeping while we wait.

This is a terrible solution because we can not know how long we will have to wait for the event. This means we have to wait for one long time period, or we have to periodically poll to see if the event has fired.

public delegate void SingleParamTestDelegate(int key, string value);
 
Real Time Web Analytics