I have use the MSDN code sample to create a Async TCP server (using sockets, and beginaccept, etc, not Tcplistener or TcpClient), and converted it some to work in a windows form. I got that working, sending all information to a Msgbox as it is transfered from the Console application for the client, no bugs were in this part of the code as far as I know. But on attempting to change Textbox1 in Form1, I realized that I couldn't (it was in the original thread, whereas the message was in the async tcp thread). I have spent a few days trying to learn to use the invoke statement. Seems it is working, as the textbox does get changed to reflect my stream that I recieve from the client. BUT and there is always a BUT I guess, I now get this error at the last End Sub of my async server code.
Getting System.InvalidOperationException was unhandled
The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
this is the code I added to the server code to invoke the textbox1 in form1.
Expand|Select|Wrap|Line Numbers
- Public Class AsynchronousSocketListener
- ' Thread signal.
- Public Shared allDone As New ManualResetEvent(False)
- Delegate Sub UpdateTextBox(ByVal message As String)
- Private Shared Sub Handler1(ByVal strInMessage As String)
- Dim f As Form1 = My.Application.OpenForms("Form1")
- f.Invoke(New UpdateTextBox( _
- AddressOf f.UpdateMessage), New Object() {strInMessage})
- End Sub
Expand|Select|Wrap|Line Numbers
- Public Sub UpdateMessage(ByVal strInMessage As String)
- Me.TextBox1.Text = strInMessage & vbCrLf & Me.TextBox1.Text
- End Sub
Expand|Select|Wrap|Line Numbers
- Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
- ' Retrieve the socket from the state object.
- Dim handler As Socket = CType(ar.AsyncState, Socket)
- ' Complete sending the data to the remote device.
- Dim bytesSent As Integer = handler.EndSend(ar)
- Handler1("Sent " & bytesSent & " bytes to client." & vbCrLf & Form1.TextBox1.Text)
- handler.Shutdown(SocketShutdown.Both)
- handler.Close()
- ' Signal the main thread to continue.
- allDone.Set()
- 'Form1.TextBox1.Text = "Sent " & bytesSent & " bytes to client." & vbCrLf & Form1.TextBox1.Text
- End Sub 'SendCallback
Expand|Select|Wrap|Line Numbers
- Handler1("Sent " & bytesSent & " bytes to client." & vbCrLf & Form1.TextBox1.Text)
To some this code may look femiliar as I used an example that was posted on these forms.
Thanks in advance, and if you need more information feel free to ask, this is just a pet project for me, but something I would really like to fix, my whole project seems to depend on it.