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:
- Call the first method, which returns a number of guids.
- 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