【发布时间】: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.InternalSet
1.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