Thursday, July 17, 2008

Start of Blog - Thread crossing C#

This is my first post for the my bog. I have been developer for over 15 years now and have seen a huge number of changes in the industry. I think most of my posts will be random hence if I can write something up here that I found difficult to solve at first and there didn't seem to be an easy to understand solution on the net.

My first post is about the unpleasant experience of upgrading one of my programs from Visual Studio 2003 to 2005. I was continually getting an exception when I was trying to update a listveiw in the main form from a thread. Due to time constraints most code I write is buggy however software needs to put out there and there is usually very little testing done at my end.

After a bit of searching I came to realise that the inital code I had written wasn't correct and I shouldn't have been calling the main form from the thread the way I did. Hence the use of these mystical items called "Delegates". I plondered for several hours trying to use the sample on the net to no avail, until one of my collegues showed me the way, thankfully!!!

Intially in my thread class I would just call the mainform listview like this:

listview1.Items[row].SubItems[column].Text = "Running ";


This failed miserably in VS2005, however the simply solution is as follows, all should be written in your thread class:

delegate void Updatelistview1Invoker(ListView listview1, int row, int column, string message);

private void MainThread_Updatelistview1(ListView listview1, int row, int column, string message)

{ listview1.Items[row].SubItems[column].Text = message; }

public void Updatelistview1(ListView listview1, int row, int column, string message)
{
listview1.Invoke(new Updatelistview1Invoker(MainThread_Updatelistview1), new object[] { listview1,row,column,message});
}

// In your code Call the following to update a particular point in your listveiw

Updatelistview1(listview1, row, column, "Running"));


Anyway I hope this helps someone out there. back to coding....

No comments: