C# 在c中通过多线程从两个不同的数据库表中获取值#
我不熟悉多线程,我试图通过多线程从两个不同的数据库表中获取值,但我得到了一个线程安全错误。下面是我的代码C# 在c中通过多线程从两个不同的数据库表中获取值#,c#,.net,multithreading,.net-core,C#,.net,Multithreading,.net Core,我不熟悉多线程,我试图通过多线程从两个不同的数据库表中获取值,但我得到了一个线程安全错误。下面是我的代码 object questionList = null; object subjectList = null; Thread t1 = new Thread(() => { questionList = _context._Question.Where(
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 wait和.ToListAsync()
对数据库进行非阻塞调用
public async Task MyMethod() {
//...
questionList = await _context._Question
.Where(Question => Question.Prof_ID == id && Question.Isverified == "No")
.ToListAsync();
subjectList = await _context._Subjects.ToListAsync();
}
使用异步等待和
ToListAsync
。不要创建新线程。DbContext不是线程安全的。你需要一个单独的例子你能给我举个例子吗?需要更多关于你到底想做什么的细节。好的。我试图从两个不同的表中获取值。但我不希望它是由主线程,这就是为什么我创建了两个不同的线程。_context是我与相应数据库的连接,可能也会有用“MultipleActiveResultSets=True”