Form.Invoke() got me down

S

Steve

I need to update my UI from a Process or worker thread. I did some readinf
and basically ended up adapting an MS example to fot my needs. It all made
sense until I tried it :)

My process makes calls to a Singleton logger class which in turn makes calls
to a delegate to add items to a listbox in my WinForm.

Here is the code that I have in my Form class to log output
<code>
delegate void AddOutputItem(string msg);

public void LogOutput(string msg)
{
ListViewItem item = new ListViewItem(msg);


if (this.listView_Output.InvokeRequired)
{
try
{
AddOutputItem d = new AddOutputItem(LogOutput);
this.Invoke(d, new object[] { msg });
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
else
{
this.listView_Output.Items.Insert(0, item);
}
}
</code>


The above code seems to work correct until it gets to the Invoke() call.
That is, UI thread calls to LogOutput have InvokeRequired = false and the
calls coming from my Process have it set to true. Once it hits that
Invoke() it hangs. No exceptions, nothing.. jsut stalls out.

Anyone have any ideas? Without exceptions I'm not really sure what to do.

Thanks for reading,
Steve
 
B

bobbychopra

Here is a sample:

private delegate void UpdateItemHandler(string msg);

private void MethodCalledFromEitherBackgroundOrUIThread( string data
) {
// Check if Method called from the non-UI thread
if( lv.InvokeRequired ) {
lv.Invoke( new UpdateItemHandler( UpdateItem ), new object[]{
"hello world msg"} );
}
else {
UpdateItem("how are you msg");
}
}

private void UpdateItem(string message ) {
lv.Items.Add( message );
....
}

Try and see if something like this works. In your scenario, you set
AddOutputItem to be the same public method LogOutput. So, the
background thread enters the LogOutput method and then you call Invoke,
which causes a switch to the foreground thread to update the UI
control, meanwhile the Invoke should have returned and exited the
function. I don't know why your background thread is not exiting the
function. However, try something like the sample above, where the
delegate is different and see if that would solve your problem.

Sincerely,
Bobby
 

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

Top