2011-06-27 206 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

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