我有一个简单的 TCP/IP 程序来从机器读取数据并将其写入文本文件。我想将它作为 Windows 服务运行,以便在没有任何干预的情况下将数据连续写入文本文件。现在,当我尝试在 Visual Studio 的 Debug模式下运行该程序时,它正在从机器读取数据并保存到文本文件中,但是一旦我将其添加为 Windows 服务并尝试启动该服务,它就会提供以下信息错误信息..
windows service could not start the service on the local computer
error:1053 The service did not respond to the start or the control request in a timely fashion
这是我的主要应用程序代码..
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
这是我使用 TCP/IP 与机器通信并将数据读/写到文本文件中的代码..
protected override void OnStart(string[] args)
{
ipaddress = "";
int port = int.Parse("");
textfileSaveLocation = "";
byte[] data = new byte[1024];
string stringData;
IPAddress ipadd = IPAddress.Parse(ipaddress);
IPEndPoint ipend = new IPEndPoint(ipadd, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = false;
try
{
sock.Connect(ipend);
}
catch (Exception dfg)
{
return;
}
try
{
buf = String.Format("SMDR", "PCCSMDR");
bBuf = Encoding.ASCII.GetBytes(buf);
sock.Send(bBuf);
while (true)
{
data = new byte[1024];
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
string df = "";
try
{
FileStream dr = new FileStream(textfileSaveLocation, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
StreamReader fg = new StreamReader(dr);
df = fg.ReadToEnd();
fg.Dispose();
dr.Dispose();
}
catch (Exception dfjdfs)
{
}
try
{
FileStream cd = new FileStream(textfileSaveLocation, FileMode.Create);
StreamWriter cdf = new StreamWriter(cd);
cdf.WriteLine(df);
cdf.WriteLine(stringData);
cdf.Dispose();
cd.Dispose();
}
catch (Exception hgy)
{
}
}
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
catch (Exception DFGFD)
{
}
}
我使用此程序的唯一目的是通过安装程序将其作为 Windows 服务运行并启动该服务。服务启动后,它应该从机器的给定 ip 和端口读取数据并将其保存到文本文件中。我还需要这项服务来持续监控来自机器的数据,一旦新数据到达机器,它应该读取和写入文本文件。
我需要在程序中实现多线程吗?
最佳答案
系统期望 OnStart
方法及时返回(约 30 秒),因此需要将长时间运行的任务(如监控数据)移至另一个线程。这可以很简单:
private System.Threading.Thread _thread;
protected override void OnStart(string[] args)
{
_thread = new Thread(DoWork);
_thread.Start();
}
private void DoWork()
{
// create and monitor socket here...
}
请注意,虽然您的 while (true)
循环足以让线程保持运行,但它很难在服务停止时停止它。为此,我使用 ManualResetEvent
像这样。
using System.Threading;
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
private void DoWork()
{
// initialize socket and file
// thread loop
while (!_shutdownEvent.Wait(0))
{
// read socket, write to file
}
// close socket and file
}
protected override void OnStop()
{
_shutdownEvent.Set();
_thread.Join(); // wait for thread to stop
}
关于c# - 在 c# 中作为 Windows 服务运行时,TCP/IP 套接字不从机器读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166680/