I know there is a better way to do this. I’m fairly new to multithreaded programming, however raising my event on a new thread like the code below allows my application to get a higher FPS with the Kinect.
When the object of my KinectService class is initalized, inside that method I do this:
Thread t = new Thread(() =>
{
sensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(sensor_AllFramesReady);
KinectSensor.KinectSensors.StatusChanged += new EventHandler<StatusChangedEventArgs>(Kinects_StatusChanged);
});
t.Start();
Which in turn calls this method:
void sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame == null)
{
return;
}
byte[] pixels = GenerateColoredBytes(depthFrame);
int stride = depthFrame.Width * 4;
BitmapSource test = BitmapSource.Create(depthFrame.Width, depthFrame.Height,
96, 96, PixelFormats.Bgr32, null, pixels, stride);
test.Freeze();
if (FrameChanged != null)
{
FrameChanged(test);
}
}
}
FrameChanged(test) passes the newly created bitmap back to the viewmodel which then updates the source of an image. Is this a terrible way to do this? Giving an event it’s own thread feels wrong, however it makes my application run a lot faster. Any pointers?
Events are fired on the same thread that called them, and there isn’t anything in the documentation for
KinectSensor.AllFramesReadyto say otherwise.So in your code sensor.AllFramesReady won’t fire another event until your event handler (
sensor_AllFramesReady) returns.A better way to do it possibly is to change your event handler to spawn off a thread and immediately return. I.e.
You will need to do some synchronisation though within frameReadyThread to ensure that the following is true,