await GetKinect()

In the first blog post about FluentKinect I’ve mentioned that I’m not very happy with the actual process of getting a KinectSensor instance from the KinectSensors collection.

FluentKinect has now been updated and the KinectConnector’s static method GetKinect is now awaitable.

If you now call KinectConnector.GetKinect() and no KinectSensor is connected to your PC a new Task is started that listens for StatusChanged events of the KinectSensor collection. If you later plugin a Kinect controller the Task returns the connected KinectSensor instance.

KinectConnector’s GetKinect method:

public static Task<KinectSensor> GetKinect()
{
	return Task.Factory.StartNew<KinectSensor>(() =>
	{
		if (kinectSensor != null) return kinectSensor;

		var kinect = KinectSensor.KinectSensors
							.FirstOrDefault(_ => _.Status == KinectStatus.Connected);
		if (kinect != null)
		{
			kinectSensor = kinect;
			return kinectSensor;
		}

		using (var signal = new ManualResetEventSlim())
		{
			KinectSensor.KinectSensors.StatusChanged += (s, e) =>
			{
				if (e.Status == KinectStatus.Connected)
				{
					kinectSensor = e.Sensor;
					coordinateMapper = new CoordinateMapper(kinectSensor);
					signal.Set();
				}
			};

			signal.Wait();
		}

		return kinectSensor;
	});
}

How to use it:

var kinect = await KinectConnector.GetKinect();
kinect.Start();

It’s not thread safe at the moment but there are a few improvements now in my opinion.

    • You can start and debug your actual program without a Kinect controller connected because no more exception is thrown. This helps with Kinect programming on a plane for example. ;-)
    • Your programm starts faster because GetKinect returns immediately
    • Since GetKinect returns a Task you get the ability to await the result

The code was pushed to GitHub and the nuget package FluentKinect has been updated as well.

Looking forward to new improvements!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s