Tuesday, August 21, 2007

Threading adventures update

So after speaking with the resident multi-threading guru, I came to the conclusion that, albeit an obvious one, still disappoints me.

See, the problem with my model was that I was trying to "push" the actions in the events onto the form instead of "pulling" the data in and forgetting about it. So unfortunately,

public frmTestBed(NitonXL800 gun)
{
InitializeComponent();

if (gun != null) tester = gun;
else tester = new NitonXL800();

tester.DataReceived += new ComDeviceDataReceivedEventHandler(tester_DataReceived);
tester.PortClosed += delegate(object sender, EventArgs e) { StopProgress(); };
}

void tester_DataReceived(object sender, ComDeviceEventArgs e)
{
txtOutput.Text = tester.Buffer;
}


Is completely out of the question, and must be replaced with:

public frmTestBed(NitonXL800 gun)
{
InitializeComponent();

if (gun != null) tester = gun;
else tester = new NitonXL800();

tester.DataReceived += new ComDeviceDataReceivedEventHandler(tester_DataReceived);
}

void tester_DataReceived(object sender, ComDeviceEventArgs e)
{
GetData updater = delegate(string data) { txtOutput.Text = data; StopProgress(); };
txtOutput.BeginInvoke(updater, e.DataRecieved);

}

My hope with this whole thing was to have the NitonXL800 object do all the marshaling for the developer, allowing the first solution. The problem he helped me realize was that "tester_DataRecieved" will always exist in a separate thread since it actually exists inside "tester". So again, getting the data from the thread is easy, just have BeginInvoke do the marshaling, but the simple truth is that it's just not "nice" to manipulate the form from the child thread, even though it is essentially owned by the form's thread.

But really, this whole problem was nothing but a design issue: Why would you want some random class modifying your form, anyway, even if it does exist in your thread? That's like my form knowing what the Baud Rate of my serial port is!

Now how exactly BeginInvoke pulls off the execution of StopProgress would definitely be an interesting conversation...

No comments: