Trying to get values from two different table of database by multithreading in c#

Viewed 85

I am new to multithreading and I am trying to get value from two different tables of database through multithreading but i am getting an error of thread safe. below is my code.

                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 is the error i am getting.

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

Why I am getting this error and how can i resolve it. How can i get value from 2 different table of database? Thanks

1 Answers

DbContext is not thread safe, hence the errors

Use async-await and .ToListAsync() to make non blocking calls to the database.

public async Task MyMethod() {

    //...

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

    subjectList = await _context._Subjects.ToListAsync();

}
Related