Oleg Skripnyak
Oleg Skripnyak

Reputation: 311

IEnumerable PLINQ yield

I have a function which returns IEnumerable which iterates objects in Inbox through MAPI, but its relatively slow, so i'm going to create a pool of connections and use them in multi-threaded fashion. Is it possible to use PLINQ in the thousands of unexpensive threads ?

Upvotes: 0

Views: 447

Answers (2)

George Mamaladze
George Mamaladze

Reputation: 7931

This is an idea of a PLINQ solution for your task:

public IEnumerable<IMessage> GetMessagesParallel(IEnumerable<IConnection> connections)
{
    return connections
        .AsParallel()
        .WithDegreeOfParallelism(10)
        .SelectMany(connection => GetMessages(connection));
}

This method accepts a number of ready to use connections. 10 threads will be started pulling messages from each connection paralelly. GetMessages is the method which actually pulls messages.

Upvotes: 0

Douglas
Douglas

Reputation: 54897

If, by “through MAPI”, you’re referring to the Outlook Object Model (as available in VSTO), then don’t use threading (whether through PLINQ or explicitly). The Outlook Object Model marshals all invocations back onto the main thread, making the process slower than if you were to run them directly from the main thread itself.

From Selecting an API or Technology for Developing Outlook Solutions:

All calls to the Outlook object model and PIA execute on Outlook’s main foreground thread. The only threading model that the Outlook object model supports is single-threaded apartment (STA). Calling the Outlook object model or PIA from a background thread is not supported and can lead to errors and unexpected results in your solution.

If you want to multi-thread access to MAPI using managed code, your best bet is the Redemption library (commercial third-party solution).

Upvotes: 2

Related Questions