C#中的Windows服务启动失败 [英] Windows Service in C# Start Failed

查看:70
本文介绍了C#中的Windows服务启动失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Everyone,

Hello Everyone,

我有一个用C#编写的Windows服务,它使用TcpListener来侦听来自客户端的请求。服务已成功安装,但当我尝试运行时,它会向我显示错误消息 

I have a windows service written in C# that is using TcpListener to listen requests from clients. Service is installed successfully, but when i am trying to run it's giving me error message 

以下是OnStart方法中的代码

Here is code in OnStart Method

protected override void OnStart(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Library.WriteErrorLog("Server Started");
            clientSocket = serverSocket.AcceptTcpClient();
            Library.WriteErrorLog("Ready to Accept");

            while ((true))
            {
                try
                {
                    NetworkStream networkStream = clientSocket.GetStream();
                    string dataFromClient;
                    byte[] bytesFrom = new byte[10025];

                    if (networkStream.DataAvailable)
                    {
                        networkStream.Read(bytesFrom, 0, 100);
                        dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf('\0'));

                        Library.WriteErrorLog("Data from Client" + dataFromClient);
                        networkStream.Flush();
                    }
                }
                catch (Exception ex)
                {
                    Library.WriteErrorLog(ex.Message.ToString() + " | Exception in Main");
                }
            }
        }

出现此错误的原因可能是什么。请指导。

What could be possible reason of this error. please guide.

Jazaib Hussain

Jazaib Hussain

推荐答案

答案在错误消息中。 将网络处理移出OnStart方法,以便它立即返回服务控制器。 它可能应该在一个单独的主题中。


The answer is in the error message.  Move the network processing out of the OnStart method so that it returns to the service controller without delay.  It should probably be in a separate thread.


这篇关于C#中的Windows服务启动失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆