Asynchronous Threading Help

  • Thread starter Thread starter Pug Fugly
  • Start date Start date
P

Pug Fugly

I am unable to call the .Show() method on a form that I have passed
through .BeginInvoke as the AsyncState parameter. I can get back the
form correctly after the .EndInvoke is called in the callback, but the
process still seems to be on a different thread even though the
..EndInvoke finished running. I get "Controls created on one thread
cannot be parented to a control on a different thread." Which I know
is not allowed, but I thought once .EndInvoke is done running I should
be back to the original thread. The form is a module variable so it
is not a scope problem. The only way I can get the form to show is if
I create a delegate for the .Show() and call that with .Invoke(). But
after that, I cannot bind to it's datagrid because I get the same
error as above. It seems like I never return back to the same thread,
or the threads are never aborting. What am I missing here?

Thanks,
Slavisa
 
Hi, Pug

After EndInvoke finished running - where are you? Because you do EndInvoke
from BeginInvoke delegate you are definitely in some thread - not the UI
one. To return to UI thread you should use form.BeginInvoke and form must
exist on UI thread.

I would suggest to trace threads using Console.WriteLine or Debug.Print -
you will see that you try to update ui form on non-ui thread. That's why you
have problem.

HTH
Alex
 
Thank for your suggestion Alex. You were right. The entire callback
function is in a completely different thread than the function from
where I called my .BeginInvoke. When you said "To return to UI thread
you should use form.BeginInvoke and form must exist on UI thread,"
what function did you mean that I would call the .BeginInvoke for. I
thought that .BeginInvoke can only be called on delegates, not on
forms. The form is in the UI thread which is the same thread that the
..BeginInvoke is being called from. I just need to get back to that
thread after my .EndInvoke comes back.

Thanks,
Slavisa
 
Hi, Pug - see below

Pug Fugly said:
Thank for your suggestion Alex. You were right...When you said "To return to UI thread
you should use form.BeginInvoke and form must exist on UI thread,"
what function did you mean that I would call the .BeginInvoke for...

If you declared say myForm on UI thread and run it there initially, say Form
myForm=new MyForm() etc.
you use myForm.BeginInvoke

Even then - check if myForm.BeginInvoke executes delegate on UI thread or
not. Depending how you get to this point it might happen you have to do one
more myForm.BeginInvoke. So, you need to pass myForm reference to async
method - or set some event in async parameters.

Main lesson - don't assume, always check which thread are you on. Then you
will be able to sort this mess fairly quickly.

HTH
Alex
 
Back
Top