Cool12309
Cool12309

Reputation: 171

Using an anti-cross-thread function to return a value

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.

Upvotes: 0

Views: 537

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

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 });

Upvotes: 2

Adam Maras
Adam Maras

Reputation: 26863

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 });

Upvotes: 5

Related Questions