0

I have this code to get around the bane of everyone's existence

delegate int GetSelectedIndicesCountCallback(ListBox thing);
private int GetSelectedIndicesCount(ListBox thing)
{
 if (this.InvokeRequired)
 {
  GetSelectedIndicesCountCallback d = new GetSelectedIndicesCountCallback(GetSelectedIndicesCount);
  Invoke(d, new object[] { thing });
 }
 else
 {
  return thing.SelectedIndices.Count;
 }
 return 0;
}

The return 0 being there because it'd error without it. However, it always returns 0. I don't know how to get it to return the other value.

Cool12309
  • 171
  • 1
  • 12
  • "the bane of everyone's existence"? – RenniePet Aug 23 '13 at 03:35
  • @RenniePet Yes, this plagues everyone's coding and is by _far_ the most annoying exception you could ever think of. – Cool12309 Aug 23 '13 at 03:43
  • Well, not that it really matters, but I think you're exaggerating. It only affects WinForms programmers who get into multi-threading, and it's a direct and logical and expected consequence of the Windows system architecture. (I'm in the process of learning Android, and it's the same there if you get into multi-threading.) Anyway, when I hear "the bane of everyone's existence" I think of things like death and taxes and politicians and regex and certain programming languages that I'll refrain from naming. :-) – RenniePet Aug 23 '13 at 03:55

2 Answers2

5

The call to Control.Invoke will return the value of your method. All you have to do is cast it to int and return it.

return (int)Invoke(d, new object[] { thing });
Adam Maras
  • 26,269
  • 6
  • 65
  • 91
2

When an invoke is required, you Invoke yourself and ignore the returned value. This is why the compiler requires a return statement.

You should return the invoked results, as in:

return (int) Invoke(d, new object[] { thing });
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73