Click here to Skip to main content
15,886,083 members
Articles / Programming Languages / C#

Calling Method Asynchronously With A Timeout

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
17 Jun 2009CPOL1 min read 46.8K   9   4
How to call a method asynchronously but have 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 a 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, it's probably going to be a web farm that you're dealing with. Nevertheless, it’s good to plan for problems such as a timeout, lack of results, remote connection denials, security issues. These calls 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 whatever manner you have opted for.

Anyway the code is fairly simple and is as follows:

C#
using System;
using System.Collections.Generic;
using System.Text;

namespace Explorer3D
{
    class AsynchMethodCall
    {
        public AsynchMethodCall()
        {
            string[] usersFetched;
            //call the delegate asynchronously 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 number of users
            //indicated by the numberOfUsersToFetch parameter from a remote
            //database
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions

 
GeneralMy vote of 1 Pin
KevinAG22-Jun-09 15:27
KevinAG22-Jun-09 15:27 
GeneralCalling Synchronous Methods Asynchronously Pin
KevinAG22-Jun-09 15:10
KevinAG22-Jun-09 15:10 
I believe that you have some mis-understanding of the asynchronous methods and objects and how to use them in .NET. You can find a little bit more information here:

http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

I'm not sure what your sample code is supposed to accomplish. I know it's just sample code, but it doesn't look like you realize that calling the .EndInvoke() method will block the calling thread until the asynchronous operation has completed. So even though you block and wait for 5 seconds, you do nothing to actually cancel the asynchronous operation. Keep in mind that your asynchronous operation must actually be cancelable.

If you were to, for example, have a return statement after your 5 second wait, your asynchronous operation would still continue to run.

Asynchronous programming is not easy. But if you want a simple way to perform a task on another thread, I highly recommend using the BackgroundWorker object. It is particularly well suited for use in Windows Forms applications. While it does provide a nice object model and features, you can still abuse it and cause problems if you don't have an understanding of the underlying principles involved in asynchronous programming.
GeneralRe: Calling Synchronous Methods Asynchronously Pin
Sacha Barber22-Jun-09 21:45
Sacha Barber22-Jun-09 21:45 
GeneralRe: Calling Synchronous Methods Asynchronously Pin
Toto110724-Jun-09 4:01
professionalToto110724-Jun-09 4:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.