EF上下文和多线程



我想知道是否有人解释我在我的代码是什么错了。我在额外的线程中运行定时器。在计时器功能中,我使用EF上下文。我看到计时器功能已经工作了6次,我特别在3秒内设置间隔,只需要100行,但在我的DB中,我只看到一个工作。那么我的错误在哪里?

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private static int cnt = 0;
        private Thread thread;
        public Form1()
        {
            InitializeComponent();
        }
        private  void StartThread()
        {
            var timer = new System.Timers.Timer();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessDb);
            timer.Interval = 3000;
            timer.Start();
        }
        public void ProcessDb(object sender, System.Timers.ElapsedEventArgs e)
        {
            cnt++;
            ConnService serv = new ConnService();
            serv.UpdateConnections(cnt);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            thread = new Thread(StartThread);
            thread.Start();
            Thread.Sleep(20000);
        }
    }
    public class MyqQueue
    {
        public static Stack<int> myStack = new Stack<int>();
        public static Stack<int> myStack2 = new Stack<int>();
    }
}
namespace WindowsFormsApplication2
{
    class ConnService
    {
        public ConnService()
        {
            cnt++;
        }
        private static int cnt;
        public void UpdateConnections(int second)
        {
            MyqQueue.myStack.Push(second);
            DjEntities ctx = new DjEntities();
            var entities = ctx.Connections.Take(100).Where(c => c.State == null);
            foreach (var connection in entities)
            {
                connection.State = second;
            }
            if (second == 1)
                Thread.Sleep(7000);
            MyqQueue.myStack2.Push(second);
            ctx.SaveChanges();
        }
    }
}
 ctx.Connections.Take(100).Where(c => c.State == null)

应改为

 ctx.Connections.Where(c => c.State == null).Take(100)

您的第一个查询翻译为首先取100而不进行过滤,然后应用过滤器。

我编写的第二个查询将获取经过过滤的项,然后获取前100项。

最新更新