On Tue, 02 Sep 2008 08:05:23 -0700, Stefan Hoffmann
<st*************@explido.dewrote:
hi @all,
I've have this working piece of code in an async callback function used:
private void SetCount()
{
if (listView.InvokeRequired)
{
listView.Invoke((MethodInvoker)(() =SetCount()));
}
else
{
listItem.SubItems[1].Text = list.Count.ToString();
}
}
Can this produce an infinite loop under some circumstances?
Sure. But hopefully not in your code.
The only way it could recurse is if something in the "else" clause of the
"if" statement were to cause the SetCount() method to be called again.
You've got five different opportunities for that to happen, but it's not
likely any of them would:
-- Getting the Count property from your "list" variable
-- Calling ToString() on the result
-- Getting the SubItems property from your listItem variable
-- Indexing the result
-- Setting the Text property of the retrieved object
Assuming we're dealing with the built-in .NET classes, the first four
possibilities just shouldn't be an issue at all. Those kinds of
side-effects shouldn't be in your own code, and it's pretty much
guaranteed that they won't exist in .NET code.
As for the last, it depends a bit on the type returned by the indexer. If
you've got a way of subscribing to a TextChanged event (for example) that
is raised when the Text property is set, then you have an opportunity to
write code that is called when that assignment happens. You _could_ have
something in that code that then in turn calls SetCount() again.
But, as long as you haven't handled such an event, or in that handler you
haven't done anything that would call SetCount() again, there should be no
issues.
By the way, I really, _really_, don't like the "InvokeRequired" pattern.
I wish MSDN had never suggested it. The Invoke() method already has to do
the same check, and it correctly deals with the condition where
InvokeRequired is false by just calling the invoked delegate directly.
So, your example could much more cleanly be written like this:
private void SetCount()
{
listView.Invoke((MethodInvoker) delegate
{
listItem.SubItems[1].Text = list.Count.ToString();
});
}
I prefer the "delegate" keyword to the lambda syntax for imperatives like
this; seems more expressive to me. But of course, you can stick with the
() =syntax if you prefer.
Pete