When you set your boolean to false, the application will exit the while loop:
1) Setting your bool
to false
isDisplayActive = false;
2) will exit this loop:
while(isDisplayActive)
{
using (var frame = kinectSensor.ColorStream.OpenNextFrame(500))
{
if (frame == null) continue;
if (displayDepthStream) continue;
Dispatcher.Invoke(new Action(() => colorManager.Update(frame)));
}
}
3) So your frame will go out of scope too. Consequently it will be disposed...
using (var frame = kinectSensor.ColorStream.OpenNextFrame(500))
4) While your main thread did not yet execute the Thread.Abort
yet.
5) And thus, your CopyPixelDataTo
will be executed on an already disposed frame
object.
frame.CopyPixelDataTo(pixelData);
6) And kaboom, you have your object disposed exception.
Thread.Abort is a bad idea.
You never know how far the executing thread was before it got executed, which can lead to all kinds of nasty side effects. Read more in this Q&A: What's wrong with using Thread.Abort()
What I would do in your situation is replace the
while(isDisplayActive)
with something like
while(colorThingyThreadIsBusy)
And set the colorThingyThreadBusy
bool to false when your Thread
is ready (=done processing).
In order to gracefully close your application I'd implement a CancellationToken instead of aborting Threads.