slandau
slandau

Reputation: 24052

Threading out inside of loop to improve performance

foreach (int tranQuote in transactionIds)
            {
                CompassIntegration compass = new CompassIntegration();
                Chatham.Business.Objects.Transaction tran = compass.GetTransaction(tranQuote);

                // then we want to send each trade through the PandaIntegration
                // class with either buildSchedule, fillRates, calcPayments or
                // a subset of the three
                PandaIntegrationOperationsWrapper wrapper = new PandaIntegrationOperationsWrapper { buildSchedule = false, calcPayments = true, fillRates = true };
                new PandaIntegration().RecalculateSchedule(tran, wrapper);

                // then we call to save the transaction through the BO
                compass.SaveTransaction(tran);
            }

Two lines here are taking a very long time. There's about 18k records in transactionIds that I do this for.

The GetTransaction and SaveTransaction are the two lines that take the most time, but I'd honestly just like to thread out what happens inside the loop to improve performance.

What's the best way to thread this out without running into any issues with the CPU or anything like that? I'm not really sure how many threads are safe or how to thread manage or stuff like that.

Thanks guys.

Upvotes: 2

Views: 278

Answers (3)

Robert Levy
Robert Levy

Reputation: 29073

What do GetTransaction and SaveTransaction actually do that makes them slow? If it's work on the CPU then threading could certainly help. If the slowness comes from making database queries or doing file I/O, threading isn't going to do anything to make your disk or database faster. It might actually slow things down because now you have multiple simultaneous requests going to a resource that is already constrained.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273229

The TPL will provide the necessary throttling and managing.

//foreach (int tranQuote in transactionIds) { ... }
Parallel.ForEach(transactionIds, tranQuote => { ... } );

It does require Fx4 or later, and all the code inside the loop has to be thread-safe.
It's not clear if your GetTransaction and SaveTransaction are safe to be called concurrently.

Upvotes: 3

Haris Hasan
Haris Hasan

Reputation: 30097

You can use Parallel foreach if order doesn't matter to improve the overall performance

Upvotes: 1

Related Questions