使用 Windows 服务进行轮询
Posted
技术标签:
【中文标题】使用 Windows 服务进行轮询【英文标题】:Polling using Windows Service 【发布时间】:2017-01-22 23:52:32 【问题描述】:通过查看一些示例,我参考了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
。我试过使用这里给出的解决方案Error 5 : Access Denied when starting windows service,但是它不起作用。
【问题讨论】:
【参考方案1】:我通过使用一些更新的代码将服务属性从 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();
【讨论】:
以上是关于使用 Windows 服务进行轮询的主要内容,如果未能解决你的问题,请参考以下文章
在 Windows 上使用 C++ 中的 Select 函数进行轮询
背水一战 Windows 10 (109) - 通知(Tile): 按计划显示 tile 通知, 轮询服务端以更新 tile 通知