首页 > 解决方案 > 尝试通过c#中的多线程从两个不同的数据库表中获取值

问题描述

我是多线程的新手,我正在尝试通过多线程从两个不同的数据库表中获取价值,但我遇到了线程安全错误。下面是我的代码。

                object questionList = null;
                object subjectList = null;
                Thread t1 = new Thread(() => {
                    questionList = _context._Question.Where(Question => Question.Prof_ID == id && Question.Isverified == "No").ToList();
                });
                Thread t2 = new Thread(() =>
                {
                    subjectList = _context._Subjects.ToList();
                });
                t1.Start();
                t2.Start();
                t1.Join();
                t2.Join();

Belwo 是我得到的错误。

System.InvalidOperationException: 
'A second operation started on this context before a previous operation completed. 
Any instance members are not guaranteed to be thread safe.'

为什么我收到此错误以及如何解决它。如何从 2 个不同的数据库表中获取价值?谢谢

标签: c#.netmultithreading.net-core

解决方案


DbContext不是线程安全的,因此错误

使用 async-await 并对.ToListAsync()数据库进行非阻塞调用。

public async Task MyMethod() {

    //...

    questionList = await _context._Question
        .Where(Question => Question.Prof_ID == id && Question.Isverified == "No")
        .ToListAsync();

    subjectList = await _context._Subjects.ToListAsync();

}

推荐阅读