2011-09-18 6 views
-2
partial class TestService : ServiceBase 
{ 
    FileStream fs; 
    StreamWriter sw; 

    public TestService() 
    { 
     InitializeComponent(); 
     fs = new FileStream(@"C:\SampleLast.txt", FileMode.Create); 
     sw = new StreamWriter(fs); 
    } 

    protected override void OnStart(string[] args) 
    { 
     try 
     { 
      if (!File.Exists(@"C:\SampleLast.txt")) 
      { 
        fs = new FileStream(@"C:\SampleLast.txt", FileMode.Create); 
        sw = new StreamWriter(fs); 
      } 

      sw.WriteLine("Service start {0}", DateTime.Now.ToString()); 

      Timer timerNew = new Timer(); 
      timerNew.Elapsed += new ElapsedEventHandler(timerNew_Elapsed); 
      timerNew.Enabled = true; 
      timerNew.Interval = 4000; 
      timerNew.Start(); 

      sw.WriteLine(timerNew.Enabled.ToString()); 
      sw.Flush(); 
     } 
     catch(Exception Ex) 
     { 
       sw.WriteLine(Ex.ToString()); 
       sw.Flush(); 
     } 
    } 

    void timerNew_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     sw.WriteLine("timer is working...{0}", DateTime.Now.ToString()); 

     SqlConnection conn; 
     SqlCommand comm; 

     conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True"); 
     comm = new SqlCommand("select Text,product from Source", conn); 

     conn.open(); 
     SqlDataReader rd = comm.ExecuteReader(); 
     while (rd.Read()) 
     { 
     if (Convert.ToInt32(rd["Text"]) < 20) 
     { 
      sw.WriteLine("{0} stock state {1}", rd["product"].ToString(), rd["stock"].ToString()); 
     } 
     } 

     sw.Flush(); 
    } 

    protected override void OnStop() 
    { 
    } 
    } 

내 프로젝트에 Windows 서비스를 사용하고 싶습니다. 내가이 코드들을 사용할 때 나는 아무런 문제가 없다.SQL을 사용하는 Windows 서비스

타이머 블록에 SQL 코드를 추가 할 때 문제가 발생합니다. SampleLast.text 파일에 약간의 효과가 있습니다. 그냥 코드를 실행 OnStart() 방법. 나는 문제가 무엇인지 이해할 수 없다. 문제는 내가 sqllconnection과 sqlcommand 코드를 사용하고 타이머가 작동한다는 것이다.

+0

당신은 필요 ... :

나는 리팩토링과 using 블록을 사용을 권 해드립니다 –

+0

의견에 제안 된대로 질문을 개선 할 수 있다면 중재자의주의를 환기시키기 위해 플래그를 지정하십시오. –

+0

또한 : ** ** Timer'는 당신이 사용하고 있습니다 (당신의 코드에서 말할 수 없습니다 - 당신은'using .....'문장을 보여주지 않습니다) ?? .NET 프레임 워크에는 최소한 3 개의 다른 Timer 클래스가 있으며, 모두가 예를 들어 .NET Framework에서 똑같이 잘 작동하는 것은 아닙니다. NT 서비스 .... –

답변

2
conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True"); 
comm = new SqlCommand("select Text,product from Source", conn); 
SqlDataReader rd = comm.ExecuteReader(); 

당신은 무엇 문제는 언급하지 않는다, 그러나 당신은 결코 실제로 SQL 연결을 개방하지 않습니다, 그래서이 일을하지 말았어야. 적어도 당신이 발생하는 문제 (오류 메시지 등)의 무엇 *** 종류 * 말해 **

using(SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True")) 
using (SqlCommand comm = new SqlCommand("select Text,product from Source", conn)) 
{ 
    conn.Open(); 
    using (SqlDataReader rd = comm.ExecuteReader()) 
    { 
     //... 
    } 
} 
+0

당신의 관심에 감사드립니다. 사실 저는 그것을 열었지만 여기에 그것을 쓰는 것을 잊었습니다. 내 문제는, 사용 후 SQL 코드 타이머 dosent 작업 –