amit agarwal
amit agarwal

Reputation: 83

Async programming control issue in c#

I am using async programming in my c# and I am trying to update data into the db on checking if the records exist else add new record

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

Since here I am uploading bulk files (say around 7000) in one shot. It happens that the same StudentCode with 2 different files can comeup. Many times I have observed that ADD part of the code is executed without checking if the student exists.

What is the change I need to do so that If-Else condition is not executed till the CheckIfStudentExists is executed.

Upvotes: 0

Views: 109

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37367

Well, this code is vulnerable to race condition. Nothing stops two threads checking that student does not exists and enter block of a code where you insert student. This leads to the same student inserted twice.

What you can do is to use some synchronization technique, like locks or semaphore. I will present you the simpliest lock, but it is up to you to choose for yourself how you want synchronize threads.

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

Upvotes: 1

Beso
Beso

Reputation: 1218

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

Upvotes: 0

Related Questions