开发者

Getting results from Parallel.For

I am looking at using Parallel.For to call into a web service that takes a while to return, however, we know we can call it many times simultaneously and it doesn't take that much longer than a single call.

To that end I'm trying out the Parallel.For and I'm really wanting to sense check my ideas on how this would work. I'm probably being a little overly cautious as I don't want to screw up the application, and I want to ensure that if we go this route the entire application team is aware of what needs to be done when accessing parallel code.

Anyway, here is my current working and understanding.

public IEnumerable<HotelAvail> GetAvailability (IList<string> codes, DateTime startDate, int numNights)
{开发者_Go百科
    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;
}

The AvailService gets availability of rooms for a specified date range (startDate + numNights). The code is the identifier for the property.

I set up a result array of the correct size at the start with lots of empty slots.

Then I call the service in parallel. The service creates a new HotelAvail object and I place it in the array in the correct position.

When all is done I return the array. It should by this point be fully populated. There should be no blanks. The service does not affect any other part of system state - It just builds a web service call, calls it, and returns a result object.

Are there any issues with this that I'm not seeing.

Like I said above, I'm probably being overly cautious, but I was burned with writing multi-threaded code in more youthful and exuberant days and I don't want to make the same mistakes again.

Also, this code will ultimately end up in an ASP.NET application. I vaguely recall that it complains a lot about multi-threaded code. Any additional problems I might encounter there?


Looks OK to me, though I think PLINQ would 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();
    }


For the Asp.net question, you may very well encounter the application timing out if your method call does not return quickly. What you may want to do for this scenario is to call a method using AJAX for each code, returning a HotelAvail object when your web service call completes, updating your UI with the new information when available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜