Is LINQ To SQL Thread Safe?

2019-08-27 00:46发布

问题:

I have a server that receives and processes messages. It then calls a method that uses LINQ To SQL to add the message in the database. As messages come in, they are set onto separate threads for processing, so it is possible that I may get two threads calling my SQL method at the same time.

I am curious whether LINQ to SQL will create separate data contexts for each thread calling the method, or if the context is static. I'm also wondering if I should put a threadlock before calling SubmitChanges().

I think the question is pretty straightforward, but I will add a code snippet just in case it helps.

using (MyDataContext db = new MyDataContext(args.ConnectionText))
            {
                //  Remove records with matching iprocid and atype
                IQueryable<densgrd> rows = from grades in db.densgrds
                                           where grades.iprocid == args.DensGrd.iprocid &&
                                                 grades.atype == args.DensGrd.atype
                                           select grades;
                //  Remove any results from the database.
                foreach (densgrd remove in rows)
                {
                    db.densgrds.DeleteOnSubmit(remove);
                }
                db.densgrds.InsertOnSubmit(args.DensGrd);

                db.SubmitChanges();
            }

回答1:

Is linq to sql thread safe in of itself, absolutely not.

Is the way you are using linq to sql in your code you posted in your question thread safe, yes.

Each thread has it's own copy of MyDataContext beacuse you are making the variable inside the thread that will be using it (That is what you are supposed to do) no variables are shared between the threads you can run as many as you want without needing to perform any kind of locking.