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
.DBContext)
  {
   
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.

using
System.Threading.Tasks;

Parallel

.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.

Annonser

Kommentera

Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut /  Ändra )

Google+-foto

Du kommenterar med ditt Google+-konto. Logga ut /  Ändra )

Twitter-bild

Du kommenterar med ditt Twitter-konto. Logga ut /  Ändra )

Facebook-foto

Du kommenterar med ditt Facebook-konto. Logga ut /  Ändra )

Ansluter till %s