Get Func-y

Posted by PhubarBaz on Geeks with Blogs See other posts from Geeks with Blogs or by PhubarBaz
Published on Mon, 10 Sep 2012 13:49:59 GMT Indexed on 2012/09/10 21:39 UTC
Read the original article Hit count: 191

Filed under:
I was working on a Windows form app and needed a way to call out to a service without blocking the UI. There are a lot of ways to do this but I came up with one that I thought was pretty simple. It utilizes the System.Func<> generic class, which is basically a way to create delegates using generics. It's a lot more compact and simpler than creating delegates for each method you want to call asynchronously. I wanted to get it down to one line of code, but it was a lot simpler to use three lines.

In this case I have a MyServiceCall method that takes an integer parameter and returns a ServiceCallResult object.

public ServiceCallResult MyServiceCall(int param1)...

You start by getting a Func<> object for the method you want to call, in this case MyServiceCall. Then you call BeginInvoke() on the Func passing in the parameter. The two nulls are parameters BeginInvoke expects but can be ignored here. BeginInvoke returns an IAsyncResult object that acts like a handle to the method call. Finally to get the value you call EndInvoke on the Func passing in the IAsyncResult object you got back from BeginInvoke.

Func<int, ServiceCallResult> f = MyServiceCall;
IAsyncResult async = f.BeginInvoke(23, null, null);
ServiceCallResult result = f.EndInvoke(async);

Doing it this way fires off a new thread that calls the MyServiceCall() method. This leaves the main application thread free to update the UI while the method call is running so it doesn't become unresponsive.

© Geeks with Blogs or respective owner