[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Asynchronous web service call in C#

Posted on 2007-10-16
5
Medium Priority
?
1,056 Views
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();
      try
      {
            naspIdAl = this.PopulateNaspIDAL(this.m_gudunAL[_begin-1].ToString());
            this.m_arrIDS = new IDSet[naspIdAl.Count];
            this.PopulateIDSet(naspIdAl);
            DataAccess.InsertIDWTable(this.m_strConnectionString,this.m_gudunAL[_begin-1].ToString(),Convert.ToInt32(HelperEnum.IDWServiceInvoked),DateTime.Now,string.Empty);
                                    //DataAccess.UpdateWebServiceStart(this.m_strConnectionString,this.m_gudunAL[_begin-1].ToString());
                                    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;
                              }

WaitHandle.WaitAny(wh,this.m_intIdwTimeout,true);
                  
                              for(int _end = 1; _end <= this.m_gudunAL.Count; _end++)
                              {
                                    try
                                    {
                                          this.m_dsInventory = this.m_objInvTory.EndCircuitInventoryReport(((IAsyncResult)arHash["AR" + _end.ToString()]));
                                          if(m_dsInventory.Tables[0].Rows.Count > 0)
                                          {
                                                DataAccess.InsertIDWTable(this.m_strConnectionString,this.m_gudunAL[_end-1].ToString(),Convert.ToInt32(HelperEnum.IDWDataRetrieved),DateTime.Now,string.Empty);
                                                DataAccess.UpdateGUDUNQueue(this.m_strConnectionString,this.m_gudunAL[_end-1].ToString(),Convert.ToInt32(HelperQueueEnum.COMP),this.attemptCtr);
                                                //DataAccess.UpdateWebServiceEnd(this.m_strConnectionString,this.m_gudunAL[_end-1].ToString(),COMP);
                                                this.CreateFlatFile(this.m_dsInventory,this.m_strDelimiter,this.m_gudunAL[_end-1].ToString());
                                                this.m_dsInventory.Clear();
                                          }
                                          else
                                          {
                                                DataAccess.InsertIDWTable(this.m_strConnectionString,this.m_gudunAL[_end-1].ToString(),Convert.ToInt32(HelperEnum.NoDataRetrieved),DateTime.Now,string.Empty);
                                                DataAccess.UpdateGUDUNQueue(this.m_strConnectionString,this.m_gudunAL[_end-1].ToString(),Convert.ToInt32(HelperQueueEnum.NODATA),this.attemptCtr);
                                                //DataAccess.UpdateWebServiceEnd(this.m_strConnectionString,this.m_gudunAL[_end-1].ToString(),NODATA);
                                          }
                                    }
0
Comment
Question by:amitpanchal2105
  • 2
4 Comments
 
LVL 16

Expert Comment

by:gnoon
ID: 20091008
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
0
 

Author Comment

by:amitpanchal2105
ID: 20092455
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
0
 
LVL 16

Accepted Solution

by:
gnoon earned 2000 total points
ID: 20094339
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++) {
      requester.BeginInvoke(
            out (int)requestParams[i][0],
            ref (DateTime)requestParams[i][1],
            new AsyncCallback(ProcessResponse),
            null);
}

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

Expert Comment

by:Computer101
ID: 20294958
Forced accept.

Computer101
EE Admin
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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 viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Suggested Courses
Course of the Month18 days, 17 hours left to enroll

834 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