使用Windows服务进行轮询

7 浏览
0 Comments

使用Windows服务进行轮询

通过查阅一些样例,我参考了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))
        {
            //执行任务
            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("无效的命令。");
        }
        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
0 Comments

问题的原因是服务属性设置为"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();
}

通过将服务属性更改为"Local System Account",可以解决无法进行轮询操作的问题。同时,还需要更新代码以适应更改后的服务属性。以上代码片段展示了如何使用TcpClient进行轮询操作,并通过NetworkStream将命令发送到指定的IP地址和端口。

0