I ran into problem while executing windows service in C#, not sure but probably due to the deadlock between the thread listening to the event handler and the normal code flow. The service just hangs when an event is listened and back to the normal flow where the Thread.Sleep is executed. The windows service goes into sleep mode normally in the first time, and in the next time the duration gets automatically doubled and thereafter it never wakes up and the service moves into a "Deadlock" mode.
There is one global variable in the below snippet controller.DeviceState, which is used both by the event listener and the main flow. All the exceptions are handled. Please let me know why the code just goes into "never waking sleep mode"
Below is the general code flow:
Main service
public partial class MainService : ServiceBase
{
protected override void OnStart(string[] args)
{
try
{
ThreadStart start = new ThreadStart(MainProcess);
Thread mainProcessThread = new Thread(start);
// set flag to indicate worker thread is active
serviceStarted = true;
// start threads
mainProcessThread.Start();
}
catch(Exception ex)
{
//catch exception
}
}
string testVariable = "YES";
//Event handler
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;
string s = sp.ReadExisting();
if (s == "Wifi")
{
testVariable = "NO";
}
}
private void MainProcess()
{
try
{
int i = 0;
System.IO.Ports.SerialPort sp = new System.IO.Ports.SerialPort("COM4");
sp.Open();
sp.DataReceived += serialPort1_DataReceived;
sp.BaudRate = 9600;
sp.DataBits = 8;
sp.Parity = System.IO.Ports.Parity.None;
sp.StopBits = System.IO.Ports.StopBits.One;
sp.Handshake = System.IO.Ports.Handshake.None;
sp.DtrEnable = true;
while (testVariable == "YES")
{
i++;
//Sleep until the testVariable is set to NO
Thread.Sleep(5000);
}
}
catch(Exception ex)
{
//catch exception here
}
}
protected override void OnStop()
{
}
}