A c# application I’m developing consists essentially of performing operations on images coming from a camera and printing them on a picturebox. It has a library written in c++ that retrieves images from a webcam (imgcam), and makes copies of them (imgcam_copy), then they are delivered to the managed code who is requesting them. In turn the managed part of the application consists of a secondary thread who executes a while cycle that takes images from the unmanaged library and prints them to a picturebox.
Everything works fine and the most delicate part of everything, that is the management of dynamic resources from unmanaged to managed code seems clear to me and I’m aware of what I’m doing (at least I hope), but the problem is with the writing of the code necessary for making threads work properly. Indeed there are many things that are not clear to me, even after browsing the web for hours.
I’m compelled to print the image with UI thread, so I have to rely on Invoke.
delegate void setImageCallback(Image img);
private void showFrame(Image img)
{
if (pboxCam.InvokeRequired)
{
this.Invoke(new setImageCallback(showFrame), img);
}
else
{
pboxCam.Image = img;
}
}
I have many questions:
1) Is Invoke a costly operation? I’ve made many efforts to reduce the execution time of main operations on images, it would be disappointing to waste part of the gain in just showing the result.
2) Do you think that it is better to use synchronously Invoke or asynchronously BeginInvoke+copy of image?
3) Could it be helpful not having Image as function parameters but accessing it as member of a class ?
private delegate void setImageCallback();
private void showFrame()
{
if (pboxCam.InvokeRequired)
{
this.Invoke(new setImageCallback(showFrame));
}
else
{
pboxCam.Image = cm.bitmap;
}
}
4) maybe you won’t share my worry for the performance, but I would like to know if you share the one for thread safety. The UI thread just wants to display an image while the non-UI thread makes a copy of it, is it really unsafe to rely on an asynchronous mechanism?