
[英]How do I get two different type of values from database in C# using LINQ?
[英]Trying to get values from two different table of database by multithreading in 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();
贝尔沃是我得到的错误。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.