2011-06-27 202 views
0

我的當前.net應用程序有一個問題,是後續,當更新數據庫行或插入新行時,我的.net服務必須讀取這些更改並提交打印命令。線程和數據庫讀取建議

我想實現的功能如下:

public void OnStart() 
{ 
    ThreadMgmt pthread = new ThreadMgmt(); 
    pthread.printNotification += new pthread.DatabaseChanged(); 
    pthread.frequency = 2000; 

    ThreadStart ts = new ThreadStart(pthread.Wait); 
    Thread t = new Thread(ts); 

    t.Start(); 
} 

void ReadDataBase() {...} 

void Printing(){...} 

public class ThreadMgmt 
{ 
    public delegate void UpdateDelegate(); 

    public event UpdateDelegate Notify; 

    private int frequency {set;get;} 


    public void Wait() 
    { 
     for (int i = 0; i <= Freq; i++) 
     { 
      Thread.Sleep(this.frequncy); 
      Notify(); 
     } 
    } 
} 

但我需要約約線程和循環事件概念的一些幫助,我想知道是否有人要面對同樣的問題,如何解決它...

謝謝

+0

我沒有看到問題?什麼不起作用?還是僅僅是一個表現問題? –

+0

我想告訴應用程序,如果滿足條件不要停止工作,並繼續尋求數據庫更改 –

回答

1

這是一個簡單的解決方案。

 private bool m_stop; 
    public void Stop() 
    { 
     lock (this) 
      m_stop = true; 
    } 

    public void Wait() 
    { 
     for (int i = 0; i <= Freq; i++) 
     { 
      lock (this) 
      { 
       if (m_stop) 
       return; 
      } 
      Thread.Sleep(this.frequncy); 
      if (Notify != null) 
       Notify(); 
     } 
    } 

如果你希望發生停機更快,你可以使用Monitor.Wait和Monitor.PulseAll,但你決定做什麼之前,你應該對這些閱讀起來。

+0

什麼情況是Freq>我,Wait()函數將退出正確?所以如何告訴應用程序連續地從數據庫中彙集數據,並且如果一些屬性例如具有0值,則doWork! –

+0

@天使,看看我的新答案。 –