2016-09-15 5 views
0

일부 샘플을 검토하여 폴링에 대해 Polling Service - C#을 참조했습니다.Windows 서비스를 통한 폴링

이것은 내 코드입니다.

public partial class Service1 : ServiceBase 
{ 
    private readonly PollingService _pollingService = new PollingService(); 

    public Service1() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnStart(string[] args) 
    { 
     _pollingService.StartPolling(); 
    } 

    protected override void OnStop() 
    { 
     _pollingService.StopPolling(); 
    } 
} 

public class PollingService 
{ 
    private Thread _workerThread; 
    private AutoResetEvent _finished; 
    private const int _timeout = 60 * 1000; 
    string command = "5120000000000000000000000000000"; 


    public void StartPolling() 
    { 
     _workerThread = new Thread(Poll); 
     _finished = new AutoResetEvent(false); 
     _workerThread.Start(); 
    } 

    private void Poll() 
    { 
     while (!_finished.WaitOne(_timeout)) 
     { 
      //do the task 
      using (TcpClient newclient = new TcpClient()) 
      { 
       IAsyncResult ar = newclient.BeginConnect("192.168.0.151", 4000, null, null); 
       if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false)) 
       { 
        return; 
       } 

       NetworkStream ns = newclient.GetStream(); 
       byte[] outbytes = HexStringToByteArray(command); 
       ns.Write(outbytes, 0, outbytes.Length); 
      } 
     } 
    } 

    public void StopPolling() 
    { 
     _finished.Set(); 
     _workerThread.Join(); 
    } 

    public static byte[] HexStringToByteArray(string hexString) 
    { 
     if (hexString.Length % 2 > 0) 
     { 
      throw new Exception("Invalid command."); 
     } 
     byte[] result = new byte[hexString.Length/2]; 
     try 
     { 
      for (int i = 0; i < result.Length; i++) 
      { 
       result[i] = Convert.ToByte(hexString.Substring(2 * i, 2), 16); 
      } 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
     return result; 
    } 
} 

설치가 완료되었습니다. 그러나 서비스를 시작하려고 할 때 Windows could not start the service on Local Computer. Error 5: Access is denied이 나옵니다. 나는 여기 제공된 솔루션을 사용하여 시도했다, Error 5 : Access Denied when starting windows service, 그러나, 그것은 작동하지 않습니다.

답변

0

몇 가지 업데이트 된 코드를 사용하여 서비스 속성을 This Account에서 Local System Account으로 변경하여 해결책을 찾았습니다.

using (TcpClient newclient = new TcpClient("192.168.0.151", 4000)) 
{ 
    NetworkStream ns = newclient.GetStream(); 
    byte[] outbytes = Encoding.ASCII.GetBytes(command); 
    ns.Write(outbytes, 0, outbytes.Length); 
    ns.Close(); 
    newclient.Close(); 
}