【问题标题】:Parallel processing in Linq and foreachLinq 和 foreach 中的并行处理
【发布时间】:2014-05-27 10:30:32
【问题描述】:

这是我的代码:

        int j;
        WebShopEntities data = new WebShopEntities();
        var db = data;
        var list =
        (from line in System.IO.File.ReadLines(MyHttpApplication.GetAppDataPath() + "677254_dp_articles.TXT").AsParallel()
         where line.EndsWith(";") && !((line.StartsWith("prom_erp_partno")))
         let parts = line.Split('\t')
         select new WebShop.dp_articles
         {
             prom_erp_partno = parts[0],
             prom_mfm_partno = parts[1],
             prol_name = parts[2],
             mfm_short_name = parts[3],
             prom_prfm_id=int.TryParse(parts[4],out j)?int.Parse(parts[4]):0,
             prol_lng_id=int.Parse(parts[5]),
             prol_variant=parts[6]??null,
             vpl=parts[7]??null,
             status=parts[8],
             gross_weight=Decimal.Parse('0'+parts[9].Replace('.',',')),
             commodity_code=parts[10],
             returnable = parts[11].Replace(';', ' ').Trim()

         }).ToList();
        Parallel.ForEach(list, item =>
         {

             if (!(from x in db.dp_articles.AsParallel() where x.prom_erp_partno == item.prom_erp_partno select x).Any())
             {

                 db.dp_articles.Add(new dp_articles
                 {
                     prom_erp_partno = item.prom_erp_partno,
                     prom_mfm_partno = item.prom_mfm_partno,
                     prol_name = item.prol_name,
                     mfm_short_name = item.mfm_short_name,
                     prom_prfm_id = item.prom_prfm_id,
                     prol_lng_id = item.prol_lng_id,
                     prol_variant = item.prol_variant,
                     vpl = item.vpl,
                     status = item.status,
                     gross_weight = item.gross_weight,
                     commodity_code = item.commodity_code,
                     returnable = item.returnable

                 });
             }
             else
             {

                 var itemU = db.dp_articles.Find(item.prom_erp_partno);
                 itemU.prom_mfm_partno = item.prom_mfm_partno;
                 itemU.prol_name = item.prol_name;
                 itemU.mfm_short_name = item.mfm_short_name;
                 itemU.prom_prfm_id = item.prom_prfm_id;
                 itemU.prol_lng_id = item.prol_lng_id;
                 itemU.prol_variant = item.prol_variant;
                 itemU.vpl = item.vpl;
                 itemU.status = item.status;
                 itemU.gross_weight = item.gross_weight;
                 itemU.commodity_code = item.commodity_code;
                 itemU.returnable = item.returnable;
             }

             db.SaveChanges();
         });

我需要并行执行这些过程,但我没有关于 c# 中并行过程的任何信息。 在 Google 中快速搜索后,我发现了这些并行语法,但在我运行它之后出现了这个错误:

在创建模型时不能使用上下文。如果在 OnModelCreating 方法中使用上下文,或者多个线程同时访问同一个上下文实例,则可能会引发此异常。请注意,不保证 DbContext 和相关类的实例成员是线程安全的。

和堆栈跟踪:

[InvalidOperationException:创建模型时无法使用上下文。如果在 OnModelCreating 方法中使用上下文,或者多个线程同时访问同一个上下文实例,则可能会引发此异常。请注意,不保证 DbContext 和相关类的实例成员是线程安全的。] System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +797 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18 System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53 System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() +15 System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +53 System.Linq.Parallel.PartitionedDataSource1.InitializePartitions(IEnumerable1 source, Int32 partitionCount, Boolean useStriping) +501 System.Linq.Parallel.PartitionedDataSource1..ctor(IEnumerable1 source, Int32 partitionCount, Boolean useStriping) +92 System.Linq.Parallel.ExchangeUtilities.PartitionDataSource(IEnumerable1 source, Int32 partitionCount, Boolean useStriping) +277 System.Linq.Parallel.ScanEnumerableQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient1 recipient) +92 System.Linq.Parallel.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient1 收件人) +578 System.Linq.Parallel.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient1 recipient) +441 System.Linq.Parallel.QueryOperator1.GetOpenedEnumerator(Nullable1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings) +386 System.Linq.Parallel.QueryOpeningEnumerator1.OpenQuery() +218 System.Linq.Parallel.QueryOpeningEnumerator1.MoveNext() +32 System.Linq.Parallel.AnyAllSearchOperator1.Aggregate() +64 System.Linq.ParallelEnumerable.Any(ParallelQuery1 source, Func2 谓词) +92 System.Linq.ParallelEnumerable.Any(ParallelQuery1 source) +126 WebShop.Models.<>c__DisplayClass4f.<ArticlesParser>b__4b(dp_articles item) in c:\Users\Ahmad\Documents\Visual Studio 2013\Projects\WebShop\WebShop\Models\Ftp.cs:369 System.Threading.Tasks.<>c__DisplayClass2d2.b__23(Int32 i) +63 System.Threading.Tasks.c__DisplayClassf1.<ForWorker>b__c() +910 System.Threading.Tasks.Task.InnerInvoke() +72 System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask) +17 System.Threading.Tasks.<>c__DisplayClass11.<ExecuteSelfReplicating>b__10(Object param0) +198 [AggregateException: One or more errors occurred.] System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +3834425 System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) +10919077 System.Threading.Tasks.Task.Wait() +10 System.Threading.Tasks.Parallel.ForWorker(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action1 body, Action2 bodyWithState, Func4 bodyWithLocal, Func1 localInit, Action1 localFinally) +925 System.Threading.Tasks.Parallel.ForEachWorker(IList1 list, ParallelOptions parallelOptions, Action1 body, Action2 bodyWithState, Action3 bodyWithStateAndIndex, Func4 bodyWithStateAndLocal, Func5 bodyWithEverything, Func1 localInit, Action1 localFinally) +223 System.Threading.Tasks.Parallel.ForEachWorker(IEnumerable1 source, ParallelOptions parallelOptions, Action1 body, Action2 bodyWithState, Action3 bodyWithStateAndIndex, Func4 bodyWithStateAndLocal, Func5 bodyWithEverything, Func1 localInit, Action1 localFinally) +10893169 System.Threading.Tasks.Parallel.ForEach(IEnumerable1 source, Action1 body) +110 c:\Users\Ahmad\Documents\Visual Studio 2013\Projects\WebShop\WebShop\Models\Ftp.cs:366 中的 WebShop.Models.Ftp.ArticlesParser() c:\Users\Ahmad\Documents\Visual Studio 2013\Projects\WebShop\WebShop\Controllers\HomeController.cs:46 中的 webshop.Controllers.HomeController.Index() lambda_method(闭包,ControllerBase,对象[])+62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase 控制器,Object[] 参数)+14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +156 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 参数) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult,ActionInvocation innerInvokeState)+22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3c() +50 System.Web.Mvc.Async.c__DisplayClass45.b__3e() +225 System.Web.Mvc.Async.c__DisplayClass30.b__2f(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.c__DisplayClass28.b__19() +26 System.Web.Mvc.Async.c__DisplayClass1e.b__1b(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult,控制器控制器)+12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +28 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

此代码解析文本文件并尝试将其放入数据库或更新它(如果存在)。

【问题讨论】:

  • 你在哪里执行这段代码?
  • localhost asp.net mvc

标签: c# multithreading plinq parallel.foreach


【解决方案1】:

简而言之,您正在从多个线程同时使用 EF。这是不允许的。扫描您的所有代码并确保您没有在一个地方使用来自多个线程的相同 EF ObjectContext(等)。

您可能应该为每个线程或每个工作单元创建一个上下文。

【讨论】:

  • 你能给我解释一下吗?
  • 当然,问我一些具体的事情。在 Stack Overflow 上,您应该自己进行基础研究并在遇到困难时询问。
  • 我将此属性用于我的数据上下文:'[ThreadStatic] static WebShopEntities data = new WebShopEntities();'我删除了'var db = data;'数据上下文线程安全错误消失了,但出现了未设置为对象实例的对象引用。我该如何解决这个问题?当我进入并行foreach循环后使用断点时,我的数据库引用变为空!!!
  • 你是在所有线程上初始化 ThreadStatic 变量还是只在一个线程上初始化?
  • 我在类属性部分初始化了:namespace WebShop.Models { public class Ftp { [ThreadStatic] static WebShopEntities data = new WebShopEntities(); ....
【解决方案2】:

如果您在枚举整个结果集之前尝试使用列表项,通常会发生该错误(通常通过相关查询末尾的 .AsEnumerable() 或 .ToList() 解决)

在你的情况下,虽然我会改变这条线:

if (!(from x in db.dp_articles.AsParallel() where x.prom_erp_partno == item.prom_erp_partno select x).Any())

并删除 .AsParallel() 。 据我所知,它没有任何用处,并且可能会阻塞代码的内部位,因为尝试添加到 db.dp_articles 而其他线程仍在查询它是不安全的。

编辑

同时从这一行中删除 .AsParallel():

var list =
        (from line in System.IO.File.ReadLines(MyHttpApplication.GetAppDataPath() + "677254_dp_articles.TXT").AsParallel()

为文件的每一行创建一个并行线程,将其过滤到同一个列表中!

【讨论】:

  • 当我将代码更改为: if ((from x in db.dp_articles where x.prom_erp_partno == item.prom_erp_partno select x).ToList().Count==0) 它说: Object引用未设置为对象的实例。
  • 我删除了它,但它又说:创建模型时不能使用上下文。如果在 OnModelCreating 方法中使用上下文,或者多个线程同时访问同一个上下文实例,则可能会引发此异常。请注意,不保证 DbContext 和相关类的实例成员是线程安全的。
  • 将 db.SaveChanges 移出 Parallel 位。
  • 我改了,什么都没变
  • 好的,再读一点,似乎你不能在多个线程中使用 dataContext,因为它不是线程安全的。如果您确定要进行并行插入/更新,则必须在每个线程中创建一个数据上下文,或者恢复为直接 SQL 查询。老实说,除非它非常慢,否则我可能会完全放弃并行处理。
猜你喜欢
  • 2016-10-08
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 2016-01-03
  • 1970-01-01
相关资源
最近更新 更多