I'm writing a program which updates a display using three threads, two that both write images to the display form, and one to switch between the two when conditions are necessary. I'll include code for all three at the bottom. I've noticed that when the absence of audio prompts for the abortion of the talkingThread, and the creation & start of the neutralThread, the talking images will hang there for a few seconds, the duration varying. I suspect it has something to do with the Sleep calls at the end of the thread, that calling Abort doesn't actually dispose the thread until that sleep is cleared, but I don't know if that would affect another thread's ability to write over the display. Is there any way to ensure that the thread is disposed sooner?
Neutral Loop -
private void neutralLoop() //loop for switching to and maintaining the neutral images
{
while (true)
{
if (isBlinking) //if blinking is enabled, check whether or not to blink, and hold for 1 second if so
{
int blinkChance = rnd.Next(2);
if (blinkChance == 1)
{
myImage = this.neutralEyesClosedMap;
pictureBox1.Image = myImage;
Thread.Sleep(1000);
}
}
myImage = this.neutralEyesOpenMap; //replace neutral eyes open state, hold for 5 secs
pictureBox1.Image = myImage;
Thread.Sleep(5000);
}
}
Talking Loop -
private void talkingLoop() //loop for switching to and maintaining the talking images
{
while (true)
{
if (isBlinking) //if blinking is enabled, check whether or not to blink, and hold for 1 second if so
{
int blinkChance = rnd.Next(2);
if (blinkChance == 1)
{
myImage = this.talkingEyesClosedMap;
pictureBox1.Image = myImage;
Thread.Sleep(1000);
}
}
myImage = this.talkingEyesOpenMap; //replace neutral eyes open state, hold for 5 secs
pictureBox1.Image = myImage;
Thread.Sleep(5000);
}
}
Switch Loop
private void switchLoop()
{
neutralThread.Start();
while (true)
{
if (deviceMeter.MasterPeakValue > 0 && deviceMeter.MasterPeakValue < 1) //check for audio
{
if (talkingThread.ThreadState != ThreadState.Running && talkingThread.ThreadState != ThreadState.WaitSleepJoin) //if talkingThread isnt running (neutralThread is running), get rid of it and start talkingThread.
{
neutralThread.Abort();
talkingThread = new Thread(new ThreadStart(talkingLoop));
talkingThread.Start();
}
} else {
if (neutralThread.ThreadState != ThreadState.Running && neutralThread.ThreadState != ThreadState.WaitSleepJoin) //if neutralThread isnt running (talkingThread is running), get rid of it and start neutralThread.
{
talkingThread.Abort();
neutralThread = new Thread(new ThreadStart(neutralLoop));
neutralThread.Start();
}
}
}
}