I am a great believer in tooling that makes jobs, coding, and even the need for learning disappear. So the other day I was attempting to use “Add Service Reference” in VS 2012 to add a reference to an OData feed I had just created. I am using the release candidate and the .NET 4.5 framework, so I expect a few changes, and of course the resulting proxy has changed a little. In my investigation I discovered the Asynchronous call back mechanisms. The mechanisms did not match the new .NET Framework 4.5 Async Await pattern. I expect that the generated proxy will get updated at some point to support this, but how hard can it be to do it myself? Well like everything once you have learned how to do it, it’s easy right!!
To test new things I like to use a unit test framework to make it easy to run the code, and I created a little test helper class to act as a container for my method. The service I was using is for a application that handles an approval process for downloading from the internet, so the service proxy is called SDAReadService (Software Download Approval Read Service) and the context is called ReadModelContainer. In the code below, the key is really the Factory.FromAsync method that has a number of overloads that allows you to pass in any pair of begin and end methods with up to 3 parameters.
public class Testhelper
public static Task<IEnumerable> GetSoftwareDownloadRequestAsync()
var container = new SDAReadService.ReadModelContainer(new Uri("http://localhost:10494/readservice.svc"));
DataServiceQuery query = (DataServiceQuery)from sdr in container.SoftwareDownloadRequests
var task = Task<IEnumerable>.Factory.FromAsync(query.BeginExecute, query.EndExecute, query);
The above method can be called with the await key word.
Apart from finding an example of how to do this the only issues I had was with passing in the correct form of the Begin and end methods. I first passed them in as methods with parameters, I knew it was not right because the parameters did not make any sense, but it took me some time before I recognized that I need to pass in the method it’s self. As usual it looks right, and you think its right, until you see what is wrong.
Here is a link to a page that demonstrates how to call the query http://msdn.microsoft.com/en-us/library/dd756367(v=vs.100).aspx.
Not too difficult to understand the old way to call an Asynchronous method with a call back, and here is documentation on how to wrap it in a task. http://msdn.microsoft.com/en-us/library/dd997423.aspx.