我想知道是否有人在我的代码中解释我的错误。 我在额外的线程中运行计时器。在计时器功能中,我使用EF上下文。我看到计时器功能已经工作了6次,我特别设置了3秒内的间隔,只占用了100行,但在我的数据库中我只看到一个工作。 那么我的错误在哪里?
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();
}
}
}
答案 0 :(得分:1)
ctx.Connections.Take(100).Where(c => c.State == null)
应改为
ctx.Connections.Where(c => c.State == null).Take(100)
您的第一个查询转换为首先取100而不进行过滤,然后应用过滤器。
我写的第二个查询将过滤掉过去的项目,然后进入前100名。