+-
尝试通过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个不同的数据库表中获取价值?谢谢

最佳答案
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();

}
点击查看更多相关文章

转载注明原文:尝试通过C#中的多线程从数据库的两个不同表中获取值 - 乐贴网