Getting Results from Parallel.For

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?

+4
source share
2 answers

Looks like me, although I think PLINQ will be a little more elegant:

  public IEnumerable<HotelAvail> GetAvailability (IList<string> codes, DateTime startDate, int numNights) { return codes.AsParallel().AsOrdered().Select(code => new AvailService().GetAvailability(code, startDate, numNights)) .ToList(); } 
+3
source

For an Asp.net question, you can very quickly find the application timeout if the method call does not return quickly. What you can do for this scenario is to call the method using AJAX for each code, returning the HotelAvail object at the end of the web service call, updating your interface with new information whenever possible.

+1
source

Source: https://habr.com/ru/post/1338738/


All Articles