I just barely started programming in C# and I am running into a small issue with background threads running infinite while loops inside of them.
A little background: I am trying to make a physical notification light for Outlook. Right now I am making it in a WPF Application to just test it before I throw it in an Outlook Add-in.
I have a button that opens up a new background thread and runs a new instance of this class:
public class LightControl
{
private byte light;
public byte Light
{
get { return light; }
set { light = value; }
}
private string color;
public string Color
{
get { return color; }
set { color = value; }
}
private int delay;
public int Delay
{
get { return delay; }
set { delay = value; }
}
private bool status;
public bool Status
{
get { return status; }
set { status = value; }
}
public void notification()
{
Action<byte, string, int, bool> lightNot =
delegate(byte i, string c, int d, bool s)
{ lightLoop(i, c, d, s); };
lightNot(light, color, delay, status);
}
private void lightLoop(byte index, string color, int delay, bool state)
{
BlinkStick device = BlinkStick.FindFirst();
if (device != null && device.OpenDevice())
{
while (state)
{
device.SetColor(0, index, color);
Thread.Sleep(delay);
device.SetColor(0, index, "black");
Thread.Sleep(delay);
}
}
}
}
I have another button that feeds a false into the status member of this class which should trickle down to the private method lightLoop and kill that infinite loop. Killing the entire thread in the process.
It isn't doing that though. The loop continues to run. What could be the cause of that?
Any help on this will be greatly appreciated.
Here is how I start the thread:
private void lightStart(byte index)
{
Random random = new Random();
int randNumber = random.Next(0, 5);
LightControl light = new LightControl();
light.Light = index;
light.Color = colors[randNumber]; //random color generator just for fun.
light.Delay = 500;
light.Status = status; //global bool on the MainWindow Class
Thread lightThread = new Thread(new ThreadStart(light.notification));
lightThread.IsBackground = true;
lightThread.Start();
}
I apologize in advance for any inaccuracy in terminology still wrapping my head around all of this.