Async Execution and Thread-Safety

  • Thread starter Thread starter Stefan Hoffmann
  • Start date Start date
S

Stefan Hoffmann

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?

I've seen similar in the net, but no comments about termination...


mfG
--> stefan <--
 
Stefan Hoffmann said:
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?

I don't think so. InvokeRequired is True when the code is executing in a
different thread from that one that created the form. The Invoke method will
marshall execution into the main thread, and therefore InvokeRequired will
become False, so the second try will get into the "else" and not produce an
infinite loop.
 
hi Peter,

Peter said:
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();
});
}
This is really good idea. Thanks.


mfG
--> stefan <--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top