Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c语言中的异步编程控制问题#_C#_.net Core_Async Await - Fatal编程技术网

C# c语言中的异步编程控制问题#

C# c语言中的异步编程控制问题#,c#,.net-core,async-await,C#,.net Core,Async Await,我在c#中使用异步编程,并试图在检查记录是否存在时将数据更新到数据库中,否则请添加新记录 var existingStudent = await CheckIfStudentExists(student); // check if the Student with the StudentCode is already exist if (existingStudent is null) { await _context.Students.AddAsync(student); a

我在c#中使用异步编程,并试图在检查记录是否存在时将数据更新到数据库中,否则请添加新记录

var existingStudent = await CheckIfStudentExists(student); // check if the Student with the StudentCode is already exist

if (existingStudent is null)
{
    await _context.Students.AddAsync(student);
    await SaveChanges();
}
else
{
    student.StudentId = existingStudent.StudentId;
    _context.Students.Update(student);
    await SaveChanges();
}
因为在这里,我上传批量文件(约7000)在一个镜头。可能会出现具有两个不同文件的相同学生代码。我多次观察到,代码的ADD部分是在不检查学生是否存在的情况下执行的


我需要做什么更改,以便在执行
CheckIfStudentExists
之前不执行Else条件。

这个代码容易受到竞争条件的影响。并没有什么可以阻止两个线程检查student是否不存在,并输入插入student的代码块。这导致同一个学生插入两次

if (existingStudent == null)
{
    await _context.Students.AddAsync(student);
    await SaveChanges();
}
else
{
    student.StudentId = existingStudent.StudentId;
    _context.Students.Update(student);
    await SaveChanges();
}
您可以使用一些同步技术,比如锁或信号量。我将向您介绍最简单的
,但您可以自行选择同步线程的方式

// somewhere in a class define
private readonly object syncObject = new object();

// and use it in the method
lock(syncObject)
{
    var existingStudent = await CheckIfStudentExists(student); // check if the Student with the StudentCode is already exist

    if (existingStudent is null)
    {
        await _context.Students.AddAsync(student);
        await SaveChanges();
    }
    else
    {
        student.StudentId = existingStudent.StudentId;
        _context.Students.Update(student);
        await SaveChanges();
    }
}

如果(existingStudent==null)
?existingStudent为null和existingStudent==null两者都做相同的事情?它们是不同的。尽管这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。还有更好的办法吗?“我不确定在这种情况下是否允许我使用锁,因为它很昂贵。@amitagarwal嗯,有很多同步工具
Semaphore
SemaphoreSlim
Monitor
等等。我使用lock进行了检查。和lock不支持wait。@amitagarwal请检查该方法。它的使用方法是在
wait WaitAsync
之后立即打开try/finally块,并在
finally
中调用
Release
。受保护区域位于
try
内。