Win Services - threading problem

Oct 26 2004 2:47 PM
Hello All, I'm writing a windows service and I have a problem that I hope someone can shine some light on for me. In my OnStart method of my Service I call another class to start my thread and write to some file. Well after installing the service when I go to start my service it starts & immediately stops. I get a message that states that that happened because there was no work to perform. Well when I comment out those calls the service stays up & running and even writes to my file but the minute I uncomment them I get the same behavior as before. Can anyone tell me how to get around this. Here is the code. Which by the way I got out of WROX's book Professional C# 3rd Edition. I put a message out on there forum and 1 week later no responses. I hope I have better luck on this forum. ***************This is the OnStart methd of my service*************** /// /// Set things in motion so your service can do its work. /// protected override void OnStart(string[] args) { try { quoteServer = new QuoteServer(@"C:\Temp\quotes.txt", 6500); quoteServer.Start(); // TODO: Add code here to start your service. DateTime sDate = DateTime.Now; FileStream fs = new FileStream(@"C:\Temp\arQuoteService.txt" , FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); m_streamWriter.WriteLine("QuoteService OnStart: Service Started " + sDate + "\n"); m_streamWriter.Flush(); m_streamWriter.Close(); } catch(Exception e) { string message = "Quote Server failed in: " + e.Message; FileStream fs = new FileStream(@"C:\Temp\arQuoteService.txt" , FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); m_streamWriter.WriteLine("QuoteService OnStart: {0}\n", message); m_streamWriter.Flush(); m_streamWriter.Close(); } } *************This is the code to the class QuoteServer that gets called*************** //Constructor public QuoteServer(string filename, int port) { this.filename = filename; this.port = port; } //This is the Start method that gets called from the service public void Start() { ReadQuotes(); listenerThread = new Thread(new ThreadStart(this.Listener)); listenerThread.Start(); } protected void Listener() { try { IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0]; listener = new TcpListener(ipAddress, port); listener.Start(); while (true) { Socket socket = listener.AcceptSocket(); string message = GetRandomQuoteOfTheDay(); UnicodeEncoding encoder = new UnicodeEncoding(); byte[] buffer = encoder.GetBytes(message); socket.Send(buffer, buffer.Length, 0); socket.Close(); } } catch (SocketException e) { string message = "Quote Server failed in Listener: " + e.Message; WriteToFile(message); } }