LINQ To SQL线程安全吗? [英] Is LINQ To SQL Thread Safe?

查看:85
本文介绍了LINQ To SQL线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收和处理消息的服务器.然后,它调用使用LINQ To SQL的方法以将消息添加到数据库中.随着消息的传入,它们被设置在单独的线程上进行处理,因此有可能让我同时获得两个线程来调用我的SQL方法.

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.

我很好奇,LINQ to SQL是否会为每个调用该方法的线程创建单独的数据上下文,或者该上下文是静态的.我也想知道在调用SubmitChanges()之前是否应该放置线程锁.

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();
            }

推荐答案

linq to sql线程本身是安全的,绝对不是.

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

您在问题线程中发布的代码中使用linq进行sql的方式是安全的,.

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

每个线程都有它自己的MyDataContext副本,因为您正在使用它的线程内部创建变量(这是您应该做的),因此在线程之间没有共享变量,并且您可以运行多达您不需要执行任何锁定操作即可.

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.

这篇关于LINQ To SQL线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆