I am developing a simple windows service that opens up a socket connection and persistantly listens on a port for some data from a remote server.
I basically have one method that does the work.
I want to be able to automatically reset the connection on a given interval because the remote service is flakey and sometimes stops sending data, at which point I need to reset the connection to resume receiving data.
Lets assume that my main method is called StartRequesting()
The problem is that since the actions performed in StartRequesting are blocking, the scm is not able to determine if the method actually started or not, so the status is listed as "starting" in the service manager.
I resolved that Issue by using ThreadStart to run the method on a new thread asynchronously.
However, that has presented me with a new round of challenges.
When I try to reset the service, by setting a flag (stopRequested = true), I am doing that from another thread, and it seems that the code either ignores it doesn't act on it for some random interval.
I instantiate this code from another class (effectively the service controller onStart)
Does anyting see anything inherintly wrong with what I am doing? Why doesn't the StopRequesting Call from the scm trigger the code path that it should until like 15 minutes after it's called? (and then it throws a thread was being aborted exception)
Any insight / tips are appreciatted.
public void StopRequesting()
{
_stopRequested = true;
}
public static void StartRequesting()
{
using (Client = new TcpClient(Common.FeedHost, Common.FeedPort))
{
using (NetworkStream Stream = Client.GetStream())
{
Stream.Write(_credentials, 0, _credentials.Length);
using (BinaryReader reader = new BinaryReader(Stream))
{
int i;
try
{
while ( (i = reader.Read(_buffer, 0, _buffer.Length)) != 0)
{
data += ASCIIEncoding.UTF8.GetString(_buffer, 0, i);
_byteCount += _buffer.Length;
if ((_byteCount / 1024) >= Common.BufferSize || _stopRequested )
{
if (_stopRequested)
{
_data = String.Empty;
_byteCount = 0;
if (Stream != null)
Stream.Close();
if (Client != null)
Client.Close();
Common.ServiceStatus = Common.ServiceStatusEnum.Stopped;
}
}
}
}
}
}
}
}
===============================
public class MyServiceController
{
private static Requestor Instance = new Requestor();
protected override void OnStart(string[] args)
{
Thread thread = new Thread(new ThreadStart(Instance.StartRequesting));
thread.Start();
}
protected override void OnStop()
{
Instance.GetType().GetMethod("StopRequesting").Invoke(Instance, null);
}
}