Asynchronous web service call in C#

Posted on 2007-10-16
Last Modified: 2008-05-19
I have an application that sends 10 requests to a webservice asynchronously and waits for all the 10 responses to come back and then fires off the another 10 requests. I want modify this in such a way that suppose if i fire off 10 requests and out of these 10 requests if get back 2 responses, I want to fire 2 more requests so that the total number of requests being processed by the webservice is always 10 at any given time. How to achieve this. Please help. Below is the code that I am using to fire 10 requests asynchronously.
Hashtable arHash = new Hashtable();
WaitHandle[] wh = new WaitHandle[this.m_gudunAL.Count];
ArrayList naspIdAl;
for(int _begin = 1; _begin <= this.m_gudunAL.Count; _begin++)
      naspIdAl = new ArrayList();
            naspIdAl = this.PopulateNaspIDAL(this.m_gudunAL[_begin-1].ToString());
            this.m_arrIDS = new IDSet[naspIdAl.Count];
                                    arHash.Add("AR" + _begin.ToString(),this.m_objInvTory.BeginCircuitInventoryReport(this.m_arrIDS,this.State,this.Country,this.ProductType,this.CircuitStatus,this.BeginDate,this.EndDate,this.CallingGroup,null,null));
                                    wh[_begin-1]= ((IAsyncResult)arHash["AR" + _begin.ToString()]).AsyncWaitHandle;

                              for(int _end = 1; _end <= this.m_gudunAL.Count; _end++)
                                          this.m_dsInventory = this.m_objInvTory.EndCircuitInventoryReport(((IAsyncResult)arHash["AR" + _end.ToString()]));
                                          if(m_dsInventory.Tables[0].Rows.Count > 0)
Question by:amitpanchal2105
    LVL 16

    Expert Comment

    Create a callback method

    It's assumed that type of m_objInvTory is Z

    private void TheadPoolCallBack(IAsyncResult ar)
        // code here executed in ThreadPool thread
        AsyncResult result = (AsyncResult) ar;
        Z z_delegate = (Z) result.AsyncDelegate;
        m_dsInventory = z_delegate.EndCircuitInventoryReport(ar);
        // process for each response here

    Then use this to send a request

    this.m_objInvTory.BeginCircuitInventoryReport(this.m_arrIDS,this.State,this.Country,this.ProductType,this.CircuitStatus,this.BeginDate,this.EndDate,this.CallingGroup,new Z(TheadPoolCallBack),null)

    Finally, it's time to get rid codes of WaitAny and loop to get responses

    Author Comment

    Thanks for such a quick response. I need to update some statuses in the database after each call is completed and i get the response. If you see my code you will find that once call the endivoke function i am creating a csv file from the dataset i have received and updating a few statuses in the database. To keep doing the same i will have to pass these parameters to the asynccallback function, how is it possible to achieve that because the only thing i could pass is one object and that we are passing as objInventory ie Z. How will i find in the asynccallback that this particular request was sent for this particular input parameter and then update the statuses in the database for that parameter. Please advice. Thanks
    LVL 16

    Accepted Solution

    Forget my first post! It's syntax error.

    To match between request and response, the input parameters can be passed by reference at BeginXXX, so you can get them in the callback to determine which one.

    For example

    // declare signature of request delegate
    delegate DataSet ReqDelegate(out int param1, ref DateTime param2);

    private DataSet RequestImp(out int param1, ref DateTime param2) {
          DataSet ds = new DataSet();
          // do web service request stuff here to fill DataSet
          return rs;

    // process response here (update database, write to file)
    private void ProcessResponse(IAsyncResult ar)
        // code here executed in thread pool thread
        AsyncResult result = (AsyncResult) ar;
        ReqDelegate req = (ReqDelegate) result.AsyncDelegate;
          // define the request params
          int param1;
          DataTime param2;
          // get the response DataSet
        DataSet ds = red.EndInvoke(out param1, ref param2, ar);
          Trace.WriteLine("param1: " + param1);
        Trace.WriteLine("param2: " + paarm2);
          // do stuff with DataSet here

    // request params
    object[] requestParams = {
          new object[]{1, DateTime.MinValue},
          new object[]{2, DateTime.MaxValue}};

    // send requests asynchronously
    ReqDelegate requester = new ReqDelegate(RequestImp);
    for(int i=0; i<requestParams.Length; i++) {
                out (int)requestParams[i][0],
                ref (DateTime)requestParams[i][1],
                new AsyncCallback(ProcessResponse),

    But I just wonder why you need the web service always processing 10 requests for a period?
    LVL 1

    Expert Comment

    Forced accept.

    EE Admin

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
    The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
    The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now