c# - 如何使用一个实例的方法但不同的构造函数参数c#调用Parallel.For
问题描述
我正在调查一个错误并尝试复制一个 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 执行方法,但是我需要executorContext
在创建时传入两个不同的对象ProgramExecutionTracker
。
我怎样才能实现这一点,以便tracker.StartExecution
由具有不同执行程序上下文的多个线程调用?
解决方案
您可以在两个上下文之间来回切换:
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());
}
推荐阅读
- java - 有没有办法从 Oracle 中选择记录并锁定它们以避免被另一个请求读取?
- java - do-while 循环计算输入数字中的位数。故障排除代码
- bash - 如何编写带有条件的嵌套 bash 循环
- laravel-5 - 如何修复 laravel eloquent 和 DB 返回空项目(模型)对象
- devexpress - 使用 Include 设置有源滤波器
- c++ - 如何将 utf 字符转换为 windows-1252?
- node.js - 有没有办法使用第一个 mysql 查询的结果使用 NodeJs 运行第二个查询
- tableau-api - Tableau 基于静态列表创建布尔维度
- linux - 如何一次重命名具有不同名称的多个文件?
- node.js - Angular 2+ 服务发布数据以表达路线