Asynchronous requests can be prepared via a call to Async() on the Request object. After this you can do the actual request using any of the GET, POST, etc. methods where a callback delegate is passed as on of the arguments. When the request completes it will call back to the delegate, passing in the response from the request.
Here is one example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // Define resource type public class Cat { public string Name { get ; set ; } public DateTime DateOfBirth { get ; set ; } } // URL template (relative to service root) const string CatUrlTemplate = "/cat/{name}" ; public static void GetAsync() { // Create session pointing to service root ISession Session = RamoneConfiguration.NewSession(...)); // Setup HTTP request Request req = Session.Bind(CatUrlTemplate, new { name = "Mike" }); Console.WriteLine( "Waiting for request to finish ..." ); // Initiate asynchronous request req.AcceptJson().Async() .Get<Cat>(response => { Console.WriteLine( "Cat: {0}." , response.Body.Name); Console.Write( "Press Enter to complete: " ); }); Console.ReadLine(); } |
In the same way it is possible to register a callback delegate to be called after the request has been completed. This delegate will always be called no matter what the outcome of the operation is.
Building on the previous example, we can now include the two OnError and OnComplete handlers:
1 2 3 4 5 6 7 8 | // Initiate asynchronous request with additional handlers req.AcceptJson().Async() .OnError(e => Console.WriteLine( "Failed: {0}" , e.Exception.Message)) .OnComplete(() => Console.Write( "Press Enter to complete: " )) .Get<Cat>(response => { Console.WriteLine( "Cat: {0}." , response.Body.Name); }); |
1 2 3 4 5 6 7 | // Initiate asynchronous POST including a request body var body = ... any data object to POST ... req.AcceptJson().Async() .Post<Cat>(body, response => { Console.WriteLine( "Cat: {0}." , response.Body.Name); }); |
Have fun :-)