[英]Polling using Windows Service
通過查看一些示例,我參考了Polling Service-C#進行輪詢。
這是我的代碼。
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
Windows could not start the service on Local Computer. Error 5: Access is denied
。 我嘗試使用此處提供的解決方案, 錯誤5:啟動Windows Service時訪問被拒絕 ,但是,它不起作用。
通過使用一些更新的代碼將服務屬性從“ 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.