簡體   English   中英

c# 中的異步編程控制問題

[英]Async programming control issue in c#

我在我的 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 個)。 碰巧可以出現具有 2 個不同文件的相同 StudentCode。 很多時候我觀察到 ADD 部分代碼在沒有檢查學生是否存在的情況下被執行。

我需要做的更改是在執行CheckIfStudentExists之前不執行 If-Else 條件。

好吧,這段代碼很容易受到競爭條件的影響。 沒有什么能阻止兩個線程檢查學生不存在並輸入插入學生的代碼塊。 這導致同一個學生插入兩次。

你可以做的是使用一些同步技術,比如鎖或信號量。 我將向您展示最簡單的lock ,但您可以自己選擇同步線程的方式。

// 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();
    }
}
if (existingStudent == null)
{
    await _context.Students.AddAsync(student);
    await SaveChanges();
}
else
{
    student.StudentId = existingStudent.StudentId;
    _context.Students.Update(student);
    await SaveChanges();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM