2011-12-25 5 views
3

私のコードで何が間違っているかを誰かに説明してもらえませんか? 私は余分なスレッドでタイマーを実行します。タイマー機能では、私はEFのコンテキストで動作します。私はタイマー機能が6回働いていて、特に3秒で間隔を設定して100行しか取れないのを見ていますが、私のDBでは1つの作業しか見ません。 どこにエラーがありますか?EFコンテキストとマルチスレッド

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

答えて

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

はあなたの最初のクエリが最初のフィルタリングなしで100を取り、その後、フィルタを適用するために変換

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

に変更する必要があります。

私が書いた2番目のクエリは、フィルタリングされた項目をとり、トップ100になります。