Calling Method Asynchronously With A Timeout

As part of an ongoing project I am just about to finish, I had a need to use a 3rd party web service. Now I am quite an cautious sort of chap when it comes to using web services. So I generally try and ensure that I try and make my code as robust as possible when dealing with such code.

For example when calling a web service, there is no guarantee that the web server is not going to die, after all it could be a web service that is hosted on a single server. Of course if the web service is from a reputable source, its probably going to be a web farm that you’re dealing with. Never the less, it’s good to plan for problems. Such as a timeout, lack of results, remote connection denials, security issues. These call all lead into problems when dealing with a web service.

To this end I have written the following bit of code to allow me to call a method asynchronously but have a timeout. This code does not use a web service, but rather shows the pattern that could be used to call any method asynchronously with a timeout. Which of course fits well with the idea of calling a web service, call the web service asynchronously, wait for a reasonable time, then see if the results are available. If they are use them, if not alert the user in what ever manner you have opted for.

Anyway the code is fairly simple and is as follows

using System;
using System.Collections.Generic;
using System.Text;

namespace Explorer3D
{
    class AsynchMethodCall
    {
        public AsynchMethodCall()
        {
            string[] usersFetched;
            //call the delegate asychronously and wait for the results 
            //from the asynch call.
            fetchNumberOfUsersDelegate fetchUsers =
            getNumberOfUsers;
            IAsyncResult asynchResult =
            fetchNumberOfUsersDelegate.BeginInvoke(1000000, null, null);
            while (!asynchResult.AsyncWaitHandle.WaitOne(5000, false))
            {
                //waiting for result for exactly 5 seconds
            }
            //try and catch any nasty exception that may have occurred
            try
            {
                usersFetched = fetchUsers.EndInvoke(asynchResult);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// The delegate that will be called asynchronously
        /// </summary>
        internal delegate string[] fetchNumberOfUsersDelegate(int someValue);

        /// <summary>
        /// A supposedly long running method
        /// </summary>
        /// <param name="numberOfUsersToFetch">number of users to fetch</param>
        /// <returns>a string array of users fetched</returns>
        private string[] getNumberOfUsers(long numberOfUsersToFetch)
        {
            //do the long bit of work, say gather the the number of users
            //indicated by the numberOfUsersToFetch parameter from a remote
            //database
        }
    }
}

Advertisements

4 thoughts on “Calling Method Asynchronously With A Timeout

  1. Josh Smith says:

    Nice. Maybe adding an event to that class, which is raised upon completion (successful or not), would be a great way to make it more generic. I don’t think that the user notification logic should be in that class.

  2. sacha says:

    Josh

    You are correct..I agree that instead of the Console.WriteLine() there should be an event raised instead.

    But for the sake of this blog entry I wanted to keep it simple. This blog is more a proof of concept thing than a working pluggable-in (if that makes sense) class.

    But I whole heartedly agree with you.

  3. Linda Rawson says:

    Great Article!

    I need to use something like this but I am pretty new to WPF and I can’t even figure out how to call a web service from a WPF application written in CSharp. Everything I read says add the web reference but there is no dialog available to me. Do you also have some code that would demonstrate this?

    Thanks,
    Linda Rawson

  4. sacha says:

    Hey Linda

    I do actually have some code

    you can see this link for one that is WPF and WCF

    http://www.codeproject.com/KB/WCF/WCFWPFChat.aspx

    And this link for another one that is standard ASMX web services and WPF.

    http://www.codeproject.com/KB/WPF/3DExplorer.aspx

    But when the say add reference, they all imply that you are using Visual Studio, and its a right click in your project, and add Web Reference for VS2005 and add Service Reference for VS2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: