簡體   English   中英

並行不使用EF4.1和Automapper

[英]Parallel For Not Working With EF4.1 and Automapper

我在實現並行時遇到問題因為它似乎間歇性地導致錯誤消息。

我正在嘗試加快映射使用大量導航屬性等構建的復雜ViewModel的過程。下面的代碼是簡化的非並行版本。

var Model = MyRepository.All.AsEnumerable().Select(a => Mapper.Map<Model, ViewModel>(a));     
return View(Model);

這工作正常,我從來沒有得到任何錯誤。 知道我的ViewModel映射很復雜,我決定測試並行版本以查看它是否更快。 簡化版本是:

var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount};
ConcurrentBag<ViewModel> ViewModel = new ConcurrentBag<ViewModel>();
Parallel.ForEach(Model, options, dr => ViewModel.Add(Mapper.Map<Model,ViewModel>(dr)));
var ViewModelSorted = ViewModel.AsEnumerable().OrderBy(a => a.SortDate);
return View(ViewModelSorted);

它通常在一半的時間內完成並顯示結果。 所以它顯然更快。 但是,我現在有時會在某些部分實體類方法中獲取有關null引用異常等的錯誤消息。 即使我測試相同的數據,這些錯誤似乎也是間歇性的。 我真的不明白為什么? 代碼不會更改或更新數據庫等,而在運行代碼時,沒有其他任何內容正在更新數據庫。 在這種情況下,是否無法使用Parallel For?

更新我的錯誤信息是:

{"Object reference not set to an instance of an object."}

堆棧跟蹤:

   at SpotList.Domain.Entities.Vessel.GetNextFixture(fixture fixture) in C:\Users\Graeme\documents\visual studio 2010\Projects\SpotList\Domain\Entities\Vessel.cs:line 47
   at SpotList.WebUI.Infrastructure.AutoMap.Charterer2.ResolveCore(Vessel source) in C:\Users\Graeme\documents\visual studio 2010\Projects\SpotList\SpotList\Infrastructure\AutoMap\AutoMapperBootstrapper.cs:line 401
   at AutoMapper.ValueResolver`2.Resolve(ResolutionResult source)
   at AutoMapper.DeferredInstantiatedResolver.Resolve(ResolutionResult source)
   at AutoMapper.PropertyMap.ResolveValue(ResolutionContext context)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)

錯誤行對應於此處的代碼:

  public fixture GetNextFixture(fixture fixture)
    {
          fixtureperiod fixtureperiod = fixture.GetMostRecentFixturePeriod();

所以fixture是null但是如果我運行非並行版本,似乎永遠不會發生同樣的事情

謝謝

格雷姆

您的模型似乎是一個懶惰評估的結構,依賴於實體框架上下文。 實體框架上下文不是線程安全的。 嘗試在非並行操作中從上下文中提取所有數據,然后將映射作為並行操作進行處理。

Parallel.ForEach(Model.ToList(), ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM