Showing a Form inside a thread

  • Thread starter Thread starter TomComWinter
  • Start date Start date
T

TomComWinter

Hello,

After searching and reading for a long a time I have a little question:

I have a ClientSide of a chat program i'm programming. There is a
thread running in order to handle all the incoming data from the
server.
What I want to do is Create a new instance and Show a form after
specific data arrives from the server. The problem is that it doesn't
allow me. I know in fact that the thread that handles the incoming data
is the one trying load the new form. The porgram crashes once trying to
show the new form.

can someone please help me?

Thank you very much!
 
If I understand your description correctly the problem is that the thread
listening to the server data stream is not the UI thread. And when you try
to access components running on the UI thread, you will indeed crash the app.
You need to invoke a delegate to pass control back to the UI thread to
launch the new form.

So somewhere you have a method that will launch your new form:
private void ShowServerForm() { ... }

You declare a delegate that matches the paramaters of the method it will
call. In this case blank:
public delegate void UpdateUIDelegate();

In your method that is triggered by you worker thread you will invoke the
delegate:
this.Invoke(new UpdateUIDelegate(ShowServerForm));

This way the "ShowServerForm" method is invoked under the UI thread and
everything is back to normal.

Hope that helps,

John Scragg
 
Back
Top