Geeks With Blogs
Phubar Baz Musings of an HTML5 Programmer
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.
Posted on Monday, September 10, 2012 3:49 PM | Back to top

Comments on this post: Get Func-y

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © PhubarBaz | Powered by: