Månad: maj 2010

Parallel programming with .NET 4.0

I have just installed the new Visual Studio 2010 and testing parallel programming with the new techniques built in the new framework. It is so easy first a linq sample.

public static IEnumerable<Bet> GetBetsPlacedSinceDate(DateTime fromDate)
using (var dbContext = DbHelper
return dbContext.Bets.Where(b => b.PlacedDate > fromDate && b.ProviderId == (int)BetProvider
.Betfair).OrderBy(b => b.PlacedDate).AsParallel().ToArray();

AsParallel is the extension method that makes the query use plinq instead of the ordinary linq execution. One more sample using the parallal task instead, for this we need this using statement.



.ForEach(markets, market =>
var extendedMarketInfo = GetMarketPricesInfoUrl(market.MenuPath);
  market.MarketPricesInfoUrl = extendedMarketInfo.MarketPricesInfoUrl;

Not so hard to implement as you can se, but be aware that the iteration order is not always what you expext as the execution is running parallel on all CPU cores. You cant know if the iteration 5 is done before iteration 9, so there must be no dependency on the execution order to work properly.