Thursday, August 17, 2006

C# hypocrisy and delgates

After spending more time than what it should have, I finally got a delegate to work with an asyncronus thread. The problem wasn't the code so much as not being able to find clear instructions on the net on how to implement it.

One of the problems is that examples on the net often take the shorthand approach of putting multiple classes in a single file (or at least what could be a single file). For example:

namespace blah
{
class firstClass { ... }

class secondClass {...}
}

the compile can deal with this fine. But if you apply it to a windows form to use in a thread as I was attempting to do, the program crashes as soon as you attempt to go to that form, with the error of "System.Resources.MissingManifestResourceException" as explained on MS's support site.

I eventually had to copy and paste to notepad, delete the file and re-create it. I wasn't impressed }:( as this code is being used in production, and although I have backups of it, having to rebuild a file like this shouldn't be necessary.

So I created a class to use for the delegate. The next problem I found was the poor explanation of how a delegate needs prescisly the same parameter names as the method you are going to call (not to mention the same return type). For example:

namespace whatever
{
class Utility
{
...

public void myMethod(TextBox box, string message)
{
box.text = box.text + message;
}
}
}

namespace whatever
{
//I've separated this out to make my point...
class targetClass
{
private System.Windows.Forms.TextBox messageTB;
private string message;
delegate void myDelegate(TextBox box, string message); //notice it matches as above

...

//inside a thread
message = "the message";
myDelegate md = new myDelegate(Utility.myMethod)
this.invoke(md, new object[] {messageTB, message});

...
}
}

This may not be the most elegant solution, but it works. - maybe this will be a bit clearer on how delegates look and operate when being used in threads.

No comments: