Search code examples
c#asynchronouskinectkinect-sdk

How to make a unblocking call in csharp


I am developing a Kinect Application which does age/gender classification.I have developed a code which will take snapshots of the color stream and after cropping the image around the head joint will do gender classification on the image using face++ api.

        System.Timers.Timer myTimer = new System.Timers.Timer();
        myTimer.Elapsed += new ElapsedEventHandler(TakeImagesTimely);
        myTimer.Interval = 20000; // 1000 ms is one second
        myTimer.Start();



        public void TakeImagesTimely(object source, ElapsedEventArgs e)
        {
           this.Dispatcher.Invoke((Action)(() =>
            {
            // code here will run every 20 second

            if (X == 0 || Y == 0) { Console.WriteLine("sdsds");  return; }
                screen("Kinect123", faceImg);
                String myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                Bitmap bmp = new Bitmap(System.IO.Path.Combine(myPhotos, "Kinect123" + ".png"));
                Bitmap bmpCrop = CropBitmap(bmp, X - 100, Y - 30, 200, 100);
                BitmapSource bmpCropSrc = ConvertBitmap(bmpCrop);
                if (bmpCrop == null || bmpCropSrc == null) { return; }
                screen1("Kinect789", bmpCropSrc);
            }));
        }

Here screen function takes the snapshot of the color stream, then after cropping the image around the head coordinates, screen1 function uploads the cropped image on the cloud and calls the face++ api for age/gender classification.

My problem is that the screen1 function takes 3-4sec to do the classification which hangs the continuous streaming from the kinect.I know I have to use asynch/unblocking call for the screen1 function but cant figure how to do it.

kindly guide me through this.


Solution

  • Try wrapping the screen1 call in an async Task.

    Example:

    Task screen1Task = Task.Run( () => {
        screen1("Kinect789", bmpCropSrc);
    });
    

    This will require you to declare the async keyword on your parent method. You also need to await the screen1Task at some point as well if you do not want it to be "fire and forget".

    More examples: https://msdn.microsoft.com/en-us/library/hh195051%28v=vs.110%29.aspx