Question

I'm having some serious troubles getting communication from one thread to another working between NetworkStream.BeginRead() and a WinForms class (I'm a real newbie when it comes to topics such as threading and Asynchronous calls).

In particular, I'm connected to a remote client via a net socket, simply listening for events. When I receive one, I can correctly collect it into a string using the BeginRead() and EndRead() methods of NetworkStream, no problems. I intend to then open up a new form (using the string as a parameter in the form's constructor) so that the information can be displayed to the user. Effectively, the network event will trigger a form for the user to be opened, and the information However, I'm constantly coming across CrossThreadMessagingExceptions, and I'm not familiar enough with delegates that I'm convinced I'm doing it right. Would someone be able to point me in the right direction?

Was it helpful?

Solution

The rule is: "You can only access controls on the thread on which they created"

You async callbacks are coming back on a different thread, so you need to marshal back to the UI thread if you want to communicate between forms.

Assuming you're NetworkStream code is already in a form, you just need to use Invoke or BeginInvoke. For example:

private void MyAsyncCallback(IAsyncResult ar)
{
    var yourString = ...from your socket...;
    this.Invoke(new MethodInvoker(() => new Form(yourString)));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top