4

I'm creating a razor view that consumes a web service (not belonging to our organisation). The way the service calls are made are as follows:

  1. Call the first method, which returns a number of guids.
  2. For each of these guids, call the second service asynchronously to return the record.

I have to make the service method calls asynchronously for performance. The problem I'm having is that I currently have no way of waiting until ALL the responses are available before returning the records back to the view. I've got this far:

Method to return records to razor view:

    public List<ProactisContract> GetContractsList()
    {
        List<Guid> contractIds = GetAmendedContracts();
        GetContractDetails(contractIds);

        //Test
        System.Threading.Thread.Sleep(5000);

        return _contractList;
    }

This is the second method that loops through the guids from the first call, making a service request for each record:

    private void GetContractDetails(List<Guid> contractIds)
    {
        foreach (var recId in contractIds)
        {
            var request = new GetContractDetailsRequest { Authentication = _authorisation, ContractGuid = recId, ContractNumber = "string", SummaryOnly = true };

            AsyncCallback asyncCallback = GetContractDetailsCallBack;

            _service.BeginGetContractDetails(request, asyncCallback, _service);
        }
    }

    private void GetContractDetailsCallBack(IAsyncResult asyncResult)
    {
        var response = _service.EndGetContractDetails(asyncResult);

        lock (_contractList)
        {
            var contract = new ProactisContract
            {
                /*Assign property values*/
            };
            _contractList.Add(contract);
        }
    }

Any ideas on how I can wait until all the responses are received before returning the List<> back to the razor view?

Thanks

JimmyB
  • 195
  • 1
  • 10

1 Answers1

1

You could create a global counter variable equal to the length of contractIds and then every time a callback finishes, you decrease the counter by 1, then you do a

while (counter != 0)
{
}

where you're sleeping the threads.

Definitely not an elegant solution by any means but I think it will work. I'm sure someone else here will provide a better solution but in the meantime, mine should solve your problem.

Willwsharp
  • 702
  • 1
  • 7
  • 25