c# - 尝试通过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();
}
推荐阅读
- java - 如何在多阶段 docker build 中使用 maven 本地存储库?
- java - 代码在return语句后继续执行
- solr - solr: ltr (reranking) 结合 cursorMarks
- r - 如何为闪亮的应用程序预设小数点分隔符
- c# - 如何在 Visual Studio 项目中初始化自动映射器
- shady - osx 重新安装后,Shady 因 SyntaxError 失败
- html - 星夜动画的关键帧
- c - 创建一个游戏板
- jupyter-notebook - 在 Jupyter Notebook 中加载属于 Octave 包的包
- cmake - 将 compile_commands.json 复制到项目根文件夹