C# invoke goes bad
ListBox is a listbox ServerClient is an instance of a class which has arraylist
Arraylist pclist = new Arraylist();
temping is array of strings as
strings[] temping = new string[6];
Now, during execution... The error I get is: "Additional information: Object reference not set to an instance of an object."
this.ListBox.Invoke(new MethodInvoker(delegate
{
for (int i = 0; i < ServerClient.pclist.Count; i++)
{
// I am Alive,MyPcName,192.168.1.1,Status,NickName,datetime
temp = ServerClient.pclist[i].ToString();
temping = temp.Split(',');
ListBox.Items.Add(temping[4] + "( " + temping[3] + " )");
}
for (int i = ServerClie开发者_开发百科nt.pclist.Count; i < ListBox.Items.Count; i++)
{
ListBox.Items.RemoveAt(i);
}
}));
If I were you I'd split my Invoke function up so that the called delegate function is declared elsewhere. Having an inline function declaration like this can be bad enough to debug, but a delegate is doubly so.
I think that you'll find that by declaring your in line function in this way the compiler is assigning all variables as locals, which won't have been intialised before use.
When you remove items with RemoveAt in the last loop you have to go down instead of up, because the index of the last item decreases everytime you remove an item with RemoveAt. If you loop down this won't affect the outcome:
for (int i = ListBox.Items.Count - 1; i >= ServerClient.pclist.Count; i--)
{
ListBox.Items.RemoveAt(i);
}
精彩评论