Reputation: 31
I was wondering if somebody explain me what is wrong in my code. I run timer in extra thread. In timer function I work with EF context. I see that timer function has worked 6 times and I especially set interval in 3 seconds and take only 100 rows but in my DB I see only one work. So where is my error?
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();
}
}
}
Upvotes: 3
Views: 466
Reputation: 39956
ctx.Connections.Take(100).Where(c => c.State == null)
Should be changed to
ctx.Connections.Where(c => c.State == null).Take(100)
Your first query translates to first take 100 without filtering and then apply filter.
Second query I have written will take items filtered and then take top 100.
Upvotes: 1