简体   繁体   中英

Call method in Parallel.Foreach and save the result into the thread safe list

I have this code which is running fine in single thread

foreach (var meetingRoom in meetingRooms)
{
            try
            {
                var res = calendarService.GetEvents(meetingRoom.Email, startUtc, endUtc, lightweight, limit);
                result.AddRange(res);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
}

but the issue is the meetingRooms list contains more than 40 000 entries. I am trying to approach the Parallel.Foreach - this is what I´ve got so far:

Parallel.ForEach(meetingRooms, () => 0,(meetingRoom) =>
        {
            var res = calendarService.GetEvents(meetingRoom.Email, startUtc, endUtc, lightweight, limit);

        }
        ,
        finalResult =>
        {
            lock (result)
            {
                result.Add(finalResult);
            }
        });

I do not have luck with the understanding of how the fourth parameter localFinally works.

Please note that result and meetingRooms are the lists with different datatypes.

EDIT:

I´ve implemented the PLINQ solution as one of answers indicates. Seems like its working but the Exchange Web Services(EWS) library is not implemented for parallel calling of one of its method. Getting and error "Not a unique key!" which is thrown by Microsoft code.

You can use PLinq.

result = meetingRooms
  .AsParallel()
  .Select(meetingRoom => calendarService.GetEvents(meetingRoom.Email, startUtc, endUtc, lightweight, limit) )
  .ToList();

When you still want to use Parallel.ForEach(), the overloads with localFinally aren't so useful. Use the basics:

Parallel.ForEach(meetingRooms, meetingRoom =>
    {
        var res = calendarService.GetEvents(meetingRoom.Email, ...);

        lock (result) // only OK when you don't lock on it anywhere else
        {
            result.Add(res);
        }
    });

您还可以使用ConcurrentBag (或ConcurrentQueueConcurrentDictionary )来存储结果并避免锁定。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM