This is a WinForms C# application.
The following two snippits show two different ways of initializing an object. They are giving different results.
This works as expected:
public partial class Form1 : Form
{
private CameraWrapper cam;
public Form1()
{
cam = new CameraWrapper();
InitializeComponent();
}
This does not work (details below):
public partial class Form1 : Form
{
private CameraWrapper cam = new CameraWrapper();
public Form1()
{
InitializeComponent();
}
Inside CameraWrapper I am using a third-party SDK to communicate with a camera. I register with an event on the SDK which is called when results are available.
In case 1 (initialization inside constructor), everything works as expected and the event handler inside CameraWrapper gets called. In case 2, the event handler never gets called.
I thought that these two styles of object initialization were identical, but it seems not to be the case. Why?
Here is the entire CameraWrapper class. The event handler should get called after a call to Trigger.
class CameraWrapper
{
private Cognex.DataMan.SDK.DataManSystem ds;
public CameraWrapper()
{
ds = new DataManSystem();
DataManConnectionParams connectionParams = new DataManConnectionParams("10.10.191.187");
ds.Connect(connectionParams);
ds.DmccResponseArrived += new DataManSystem.DmccResponseArrivedEventHandler(ds_DmccResponseArrived);
}
public void Trigger()
{
SendCommand("TRIGGER ON");
}
void ds_DmccResponseArrived(object sender, DmccResponseArrivedEventArgs e)
{
System.Console.Write("Num barcodes: ");
System.Console.WriteLine(e.Data.Length.ToString());
}
void SendCommand(string command)
{
const string cmdHeader = "||>";
ds.SendDmcc(cmdHeader + command);
}
}
Not quite.
In the first case, the
CameraWrapperconstructor is called after the base class constructor forForm. In the second case, theCameraWrapperconstructor is called, then the base class constructor, then theForm1constructor body.It’s possible that something within the
Formconstructor affects the execution of theCameraWrapperconstructor.