I use Parallel.For to call a web service that takes some time to return, however, we know that we can call it many times at the same time, and it wonβt take much more time than one call.
To this end, I am trying Parallel.For, and I really want to test my ideas on how this will work. Iβm probably a little too cautious, because I donβt want to spoil the application, and I want to make sure that if we go along this route, the entire application team will know what to do when accessing the parallel code.
Anyway, here is my current work and understanding.
public IEnumerable<HotelAvail> GetAvailability (IList<string> codes, DateTime startDate, int numNights) { HotelAvail[] result = new HotelAvail[codes.Count]; Parallel.For(0, codes.Count, i => { string code = codes[i]; result[i] = new AvailService(). GetAvailability( code, startDate, numNights); }); return result; }
AvailService gets the availability of rooms for a given date range ( startDate + numNights ). code is a property identifier.
I installed an array of results with the correct size at the beginning with lots of empty slots.
Then I call the service in parallel. The service creates a new HotelAvail object, and I put it in the array in the correct position.
When everything is done, I return an array. At this point, it should be completely filled. There should be no spaces. The service does not affect any other part of the state of the system β it simply creates a call to the web service, calls it, and returns a result object.
Are there any problems with this that I do not see.
As I said above, I am probably too careful, but I was burned to write multi-threaded code in the younger and more turbulent days, and I do not want to repeat the same mistakes.
In addition, this code will end up in an ASP.NET application. I vaguely remember that he complains a lot about multithreaded code. Any additional issues I may encounter?