如何使用一个实例的方法但不同的构造函数参数c#调用Parallel.For
Posted
技术标签:
【中文标题】如何使用一个实例的方法但不同的构造函数参数c#调用Parallel.For【英文标题】:How to call Parallel.For with a method of the one instance but different constructor parameters c# 【发布时间】:2021-02-23 14:06:00 【问题描述】:我正在调查一个错误并尝试复制一个 SQL 异常 - Cannot insert duplicate key row in object with unique index . The duplicate key value. The statement has been terminated
我在单元测试中这样做是为了复制异常。
这是测试:
public void Should_Throw_Exception_When_StartExecution_Is_Called_Twice_By_Two_Different_Programs_Belonging_To_Same_Account()
//Arrange
var executorContext = new ExecutorContext
Program = new ProgramObject
ID = 100,
Account = RootAccount
,
ScheduledExecutionDate = DateTime.Now
;
var executorContext2 = new ExecutorContext
Program = new ProgramObject
ID = 200,
Account = RootAccount
,
ScheduledExecutionDate = DateTime.Now
;
var tracker = new ProgramExecutionTracker(executorContext, _dataContext);
Parallel.For(0, 5, (i) => tracker.StartExecution());
Parallel.For 是为了多次调用 start 执行方法,但是我需要在创建 ProgramExecutionTracker
时传入两个不同的 executorContext
对象。
我怎样才能做到这一点,以便tracker.StartExecution
被具有不同执行器上下文的多个线程调用?
【问题讨论】:
【参考方案1】:您可以在两个上下文之间来回切换:
public void Should_Throw_Exception_When_StartExecution_Is_Called_Twice_By_Two_Different_Programs_Belonging_To_Same_Account()
ExecutorContext[] executorContexts= new
ExecutorContext[2]; //array with 2 elements
//Arrange
executorContexts[0] = new ExecutorContext
Program = new ProgramObject
ID = 100,
Account = RootAccount
,
ScheduledExecutionDate = DateTime.Now
;
executorContexts[1] = new ExecutorContext
Program = new ProgramObject
ID = 200,
Account = RootAccount
,
ScheduledExecutionDate = DateTime.Now
;
Parallel.For(0, 5, (i) => ((new ProgramExecutionTracker(executorContexts[i%2], _dataContext)) .StartExecution());
【讨论】:
以上是关于如何使用一个实例的方法但不同的构造函数参数c#调用Parallel.For的主要内容,如果未能解决你的问题,请参考以下文章