首页 > 解决方案 > 如何使用一个实例的方法但不同的构造函数参数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由具有不同执行程序上下文的多个线程调用?

标签: c#sql.nettestingexception

解决方案


您可以在两个上下文之间来回切换:

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());
}

推荐阅读