Showing posts with label delegate. Show all posts
Showing posts with label delegate. Show all posts

Thursday, June 20, 2013

Partial Applications using Currying & Function Compositions

C# introduced Func and Action delegates in .net framework 3.5. They are part of C# 2 language specification. It also introduced expression trees and lambda expression in the same framework version. It's amazing how technologies evolve and new technologies are built on top of the existing ones. They were built on top of Generics introduce in .net framework 2.0. In this post we are going to discuss how we can use these constructs to introduce currying, partial applications and functional composition.

Previously we have discussed how we can use dynamic call site to avoid compile time check for arithmetic operations in a generic type. You can find the discussion here [http://www.shujaat.net/2012/05/c-generics-arithmetic-operators.html]. We will be assuming that calculator has been provided to us as a third party library and we will be deriving more meaningful operations (functions) from the existing methods using functional approaches. Referential transparency is the essence of functional programming providing side-effect free operations. We discussed about purely functional approach here [http://www.shujaat.net/2012/07/design-guidelines-purely-functional.html]

Currying
Currying is a transformation technique in functional programming space. It is used to convert a function with multiple parameters to a set of functions with single parameter each. It can be used to create refined algorithms where partial list of arguments can be provided to create more sophisticated operations. The nomenclature is in the honor of Haskell Curry, the creator of Haskell functional programming language. It must be remembered that the end-result of a curried version of a function should exactly be the same as its non-curried counterpart.

C# 4.0 provided optional parameters. These are the parameters with default values. If the caller doesn't want to pass arguments to those parameters then the default value is used instead. They are always at the end of the parameter list. This is opposite to the partial application case as the fixed arguments here. They would be the first parameters to a function. You might want to use these two concepts together as well. We can introduce the support for currying a function using extension methods. We can introduce these extension methods for the required overloads of Func and Action delegates. The following is an example of currying where we are converting a method with two parameters to a set of methods with single parameters.

The above code uses the Closure and Captured variables. Being a captured variable, operand1 is available inside the inner lambda expression. The whole feature is available due to closure where the life time of the context of lambda expression declaration is upgraded to the life time of expression itself allowing the use of captured variables. Actually we have discussed about closures in the context of async code execution using Dispatcher in WPF applications.

Partial application is about fixing the arguments to a function. An application has historically been referred as a set of functions. So the remaining method with some fixed arguments is referred as partial application. So we first obtain the curried version of a function and then provide fixed arguments. Wikipedia has a quick reference about the concept.

Now let's see how we can use currying and partial applications to create more meaningful operations. In the example below we are using the methods provided by the above Calculator class to derive calculatePlusPlus, calculateAdditiveInverse and calculateMultiplicativeInverse functions. Here we are fixing first arguments to the curried versions of the delegates based appropriate to the operation e.g. for calculatePlusPlus we can fix the first argument to 1.

The output of the above code would be as follows:



We are certainly not restricted to use only Func delegates. We can also use Action delegates if needed. Lets' create an extension method which curries an Action delegate with two parameters to a set of Action delegates. Don't get confused with the combination of Func and Action delegates being used here. You can just be concerned about the last Action, which refers to the actual operation. The rest of the design is just to curry it.

Here we are introducing a lambda statement to print a message specified number of times. We are assigning the statement to an Action delegate. After currying the delegate, we are creating a partial application printThreeTimes by fixing the first argument to 3. This would cause the message to be printed three times.

I can understand you might be thinking if this is possible to UnCurry a curried function or not. Actually we can do that too. Below is the extension method accepting a curried Func delegate and returning an Un-Curried version of the delegate.

Here we are UnCurrying a curried version of divide operation from Calculator. We are then calling it using the specified arguments as follows:

Functional Composition to construct data / processing chains
Functional composition is the method where multiple functions are used in a serial fashion in such a way that the output of one method serves as the input of other method.This can be used to build processing chains. I am deliberately not calling it a pipeline because a pipeline should have producer / consumer based intermediate queues. We have discussed how we can implement processing pipelines during the discussion of TPL Dataflow. You can find the discussion here: [http://www.shujaat.net/2013/05/processing-pipelines-with-tpl-dataflow.html].

The processing chain created through functional composition can also be specified using extension methods. The following defines an extension method on a Func delegate with two parameters. After getting the result from the first, it just passes the results to the second Func delegate. Obviously the next element in the chain should have only one parameter. After the second element completes, it just returns the result to the caller.

In the following code we are providing support of calculating percentage using the available Divide and Multiply methods from Calculator. As we know percentage of a part in a total is computed as [ percentage = (part / total) * 100 ]. So we need to obtain a curried version of Multiply & fix the first argument to 100 and use it after dividing part by the total.

It is also possible that the processing chain is not returning any data back to the caller. In this case, all the elements in the chain do pass the required data to the next element in the chain. The last element just uses the data for its purpose and nothing returns back to the caller. We can implement this using chain of Func delegates with an Action delegate at the end.

Let's see how we can use it to print the percentage of a part. Here we are using the function composition created for calculating the percentage. We are adding an element to construct a message. At the end we are using a processing element to print the message to the console. For the last element, we are using the curried version of printMessage with first argument fixed as 1.

The output of the above code would be as follows:


Saturday, December 11, 2010

WPF - ASynchronous Delegate Exception Model

In this post, we are going to discuss exception model of Asynchronous delegates. For those who have started development just starting with .net 4.0, they are old school for Task. Basically thread (including ThreadPool.QueueUserWorkItem based threads) are for providing "shoot and run" kind of flows. They don't us allow to return anything from them. If we needed to return a value, the only option we have is ASynchronous Delegate. It must be remembered that Asynchronous delegate would still be using ThreadPool thread so it will have all the benefits of using a ThreadPool thread.

Like BackgroundWorker, ASynchDelegate also has a special mechanism for dealing with exceptions raised during its operation. It is necessary to be aware of it. We will be discussing the use of ASynchDelegate in a sample WPF application. In this application, we will be taking input of two operands. The application would perform some complex calculation on these operands and display the result on the form. In order to keep the example simple, we would just sum these operands. We will not be verifying the inputs just for the same reason.


The XAML for the above display is as follows:

<Window x:Class="WpfApplication_ASynchDelegate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowASynchDelegate" Height="389" Width="595">
<Grid>
<TextBox Height="27" HorizontalAlignment="Left" Margin="138,22,0,0"
Name="textBoxOperand1" VerticalAlignment="Top" Width="311" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="138,55,0,0"
Name="textBoxOperand2" VerticalAlignment="Top" Width="311" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="138,143,0,0"
Name="textBoxResult" VerticalAlignment="Top" Width="311" />
<Button Content="Sum" Height="28" HorizontalAlignment="Left" Margin="139,88,0,0"
Name="button1" VerticalAlignment="Top" Width="143" Click="button1_Click" />
<Label Content="Operand 1" Height="27" HorizontalAlignment="Left" Margin="12,22,0,0"
Name="label1" VerticalAlignment="Top" Width="120" />
<Label Content="Operand 2" Height="27" HorizontalAlignment="Left" Margin="12,55,0,0"
Name="label2" VerticalAlignment="Top" Width="120" />
<Label Content="Result" Height="27" HorizontalAlignment="Left" Margin="12,143,0,0"
Name="label3" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>

The code behind of the above window is as follows:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private decimal getSum(decimal operand1, decimal operand2)
{
decimal sum;
sum = operand1 + operand2;

return sum;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);
decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);

Func<decimal, decimal, decimal> getSumAsynchDelegate = getSum;

getSumAsynchDelegate.BeginInvoke(operand1, operand2,
(resultASynch) =>
{
var methodDelegate = (Func<decimal, decimal, decimal>)resultASynch.AsyncState;

this.Dispatcher.BeginInvoke(
new Action(() =>
this.textBoxResult.Text =
methodDelegate.EndInvoke(resultASynch).ToString()));
},
getSumAsynchDelegate);
}
}

In the Click event handler for the button, we have assigned the text entered in two input text boxes texBoxOperand1 and textBoxOperand2 to local variables operand1 and operand2. We have introduced an asynchronous delegate. This is expected to receive two decimal arguments and returns a decimal value. In the Asynchronous delegate declaration, the last value specified is the return type.

Func<decimal, decimal, decimal> getSumAsynchDelegate = getSum;

Although Asynchronous delegate seems to be similar to the Asynchronous methods (Asynchronous Programming Model - APM) because It has BeginInvoke and EndInvoke mechanism as in ASynchronous method and BeginInvoke returns IASynchResult as ASynchronous methods. But it must be remembered that BeginInvoke returns immediately after calling the method to the calling method. As discussed here, we can call BeginInvoke to invoke an Asynchronous delegate. It seems that we have provided four arguments to it. First two are for the method parameters [It depends on how many parameters you have for the method being called]. The third argument is the callback after the method finishes execution on a different thread. The last parameter is anything we want to pass. It is copied to ASynchState of the method. We can get this value in the callback. We have passed the delegate itself to ASynchState as we don't want to declare an instance member for it.

Now we discuss the lambda for the callback which gets called when asynchronous delegate finishes execution.

(resultASynch) =>
{
var methodDelegate = (Func<decimal, decimal, decimal>)resultASynch.AsyncState;

this.Dispatcher.BeginInvoke(
new Action(() =>
this.textBoxResult.Text =
methodDelegate.EndInvoke(resultASynch).ToString()));
},

As you can see, we have obtained the delegate from ASynchState property of resultASynch(IASynchResult). The interesting thing to notice is that we have used Dispatcher to copy value to textBoxResult.Text. This is because, unlike BackgroundWorker, the callback is not executed on UI thread. In order to get the returned value from the delegate, we need to call EndInvoke on the delegate passing IASynchResult as the argument. Since the method is expected to return a decimal value, we are converting it to string before assigning to the Text property of the text box.

Even if we don't call EndInvoke on ASynchronous Delegate, it still would finish execution. It wouldn't be making sense to use this delegate though in this kind of situation, as we are not expecting any returned value. But if we don't call EndInvoke then we lose any exception caused in the method called using asynchronous delegate. It is a silent exception. This is the same thing as we discussed in BackgroundWorker. We must be aware of all these silent failures in our application as it can lead our application to be in an unexpected state.

Let's update the method as follows:

[DebuggerNonUserCode]
private decimal getSum(decimal operand1, decimal operand2)
{
decimal sum;
sum = operand1 + operand2;

if (sum > 0)
throw new Exception("What did u do!");

return sum;
}

So if we don't call EndInvoke and update the definition of the method and don't call EndInvoke, the application would never know about the exception. If we don't use try / catch block with EndInvoke and the method results in an exception, the exception could end up in DispatcherUnhandledException if we are calling EndInvoke on a UIThread. Or AppDomain.CurrentDomain.UnhandledException if we are calling it in any other thread (as in the callback of asynchronous delegate).

Monday, November 29, 2010

WPF - Dispatcher.Invoke is an overkill

In this post we discuss that executing a synchronous operation on UI threads can be an overkill. It should only be used with care. As we know, we can use Invoke and BeginInvoke on Dispatcher to execute a synchronous and asynchronous operation on UI thread respectively. Calling Invoke is an overkill.

In order to discuss this point. Let us use both, Invoke and BeginInvoke, in a sample WPF application. The following is a WPF window with two text boxes and a button.

<Window x:Class="WpfDispatcher_OperationInvocation.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="451">
<Grid>
<TextBox Height="30" Margin="175,24,30,0" Name="textBoxInvoke" VerticalAlignment="Top" />
<TextBox Height="30" Margin="175,79,30,0" Name="textBoxBeginInvoke" VerticalAlignment="Top" />
<Label Margin="14,24,0,0" Name="label1" Height="24" HorizontalAlignment="Left"
VerticalAlignment="Top" Width="133">Updated Through Invoke</Label>
<Label Height="32" HorizontalAlignment="Left" Margin="9,77,0,0" Name="label2"
VerticalAlignment="Top" Width="165">Updated Through Begin Invoke</Label>
<Button Height="32" Margin="128,0,146,82" Name="button1" VerticalAlignment="Bottom"
Click="button1_Click" >Update Text</Button>
</Grid>
</Window>

As you can see above, we have two textboxes and a button. We have also specified button1_Click as the Click handler for button1. We are using Invoke for one operation on UI thread and BeginInvoke for other. In both these operations, we are updating the text of one of the text boxes.

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

void button1_Click(object sender, RoutedEventArgs e)
{
Thread t = new Thread(
() =>
{
textBoxInvoke.Dispatcher.Invoke(
new Action(() => textBoxInvoke.Text = "Updated"));

textBoxBeginInvoke.Dispatcher.BeginInvoke(
new Action(() => textBoxBeginInvoke.Text = "Updated"));
});

t.IsBackground = true;
t.Start();
}
}

Whenever we call Invoke or BeginInvoke on a Dispatcher, we are introducing a new work item in the dispatcher queue of the dispatcher. So what is the difference between the two? The answer is that Invoke is a synchronous operation and BeginInvoke is an asynchronous operation.

When we call BeginInvoke on a Dispatcher, it pushes the work item on the queue and returns (1 in above figure) DispatcherOperation which can be used to keep on eye on the status of the execution of the delegate. The calling thread wouldn't wait for anything and goes on any other tasks (2 in above figure). On the other side, Invoke causes the work item to be pushed on the queue. It is pushed based on its DispatcherPriority. Now the calling thread is waiting for this operation to be completed. The work item keeps waiting on the Dispatcher queue when there comes her turn of execution by Dispatcher. The dispatcher executes it. Now the result is returned to the calling thread. There might be many work items in the dispatcher queue with same or greater priority values. Calling an operation like this is lethal for the calling thread cause it could be waiting for a long time.


But there might be certainly situations when you can not go without going synchronous. In the following example, we need the text entered in a text box and show it in a MessageBox.

string enteredText = "";

textBox1.Dispatcher.Invoke(new Action(() => enteredText = textBox1.Text), null);
MessageBox.Show(enteredText);

If we don't call this synchronously then we by the time we reach MessageBox.Show this item hasn't been executed by textBox1's Dispatcher so the text is not yet copied to winTitle so would be showing an empty MessageBox.

We can still wait on work item introduced in Dispatcher using BeginInvoke. Basically BeginInvoke does not have a corresponding “EndInvoke”. Many a times we need to find out when an operation ended before starting another dependent work item. BeginInvoke returns a DispatcherOperation. We can use Status property of DispatcherOperation to find this out. If it is Completed then the dispatcher is done executing this operation and we can go ahead with executing the dependent work item. We can also call Wait() on DispatcherOperation which makes this operation as synchronous which is similar to calling Invoke on Dispatcher. We need to be careful as this can lead to the same issue of deadlock as Invoke when UI and worker thread are waiting for some resource which one is needing and the other has it. DispatcherOperation also supports aborting a work item. When we abort it then it is removed from dispatcher’s queue. It’s state is set as Aborted.
DispatcherOperation dispatcherOperation = 
textBoxBeginInvoke.Dispatcher.BeginInvoke(
new Action(() => textBoxBeginInvoke.Text = "Updated"));

//Any other Task(s)

if (dispatcherOperation.Status != DispatcherOperationStatus.Completed)
{
dispatcherOperation.Wait();
}


Now the last words! Avoid using Invoke on Dispatcher when we are absolutely not sure that we need it, otherwise, use BeginInvoke if it wouldn't be making any difference.