Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27033

VS 2010 Canceling/Disposing a TCP Client from a different thread.

$
0
0
I have two threads. One is a backgroundworker which makes a connection with a TCP client and another, the UI thread which has a timer which makes sure that we know when the backgroundworker takes too long by reporting a timeout.
When the TCP client encounters an exception it takes forever for it to report it. So by making into another thread I can keep the UI active. So, when the timer reports the timeout, I would like to be able to close the tcp client connection so that I can use the backgroundworker again for another use and prevent it from throwing an error that it is still busy.
I hope this is self explanatory but here are a couple snippets of my code:

Timer code:
vb Code:
  1. CheckTimeout.Interval = 2500
  2.         'If the tcp client reported online before timeout then stop timer.
  3.         If UserStatetxt.ToLower = "online" Then
  4.             CheckTimeout.Stop()
  5.         ElseIf UserStatetxt.ToLower = "connecting..." Then
  6.             'If it still says that it is connecting then report a timeout.
  7.             txtStatus.Text = "Timeout"
  8.             'Now stop the backgroundworker from being busy by closing the Tcp client connection
  9.             bwConnect.CancelAsync()
  10.             'cancel async doesn't work
  11.             'i need something like Server.close() for my tcp client but this is another thread
  12.         End If

Backgroundworker:
vb Code:
  1. Private Sub bwConnect_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwConnect.DoWork
  2.         Dim Server As New System.Net.Sockets.TcpClient()
  3.         Try
  4.             Server.Connect(txtIP.Text, txtPort.Text)
  5.         Catch ex As Exception
  6.             UserStatetxt = "error"
  7.             UserStateEx = ex.Message
  8.         Finally
  9.             If Server.Connected = True Then
  10.                 UserStatetxt = "online"
  11.             End If
  12.             Server.Close()
  13.         End Try
  14.     End Sub

I have read the help documentation for the TCP client and of the BackgroundWorker. I have tried alternative methods of multithreading and still no result.
I need to cancel the TCP Client forcefully in order for my project to work correctly, but as I mentioned, from different thread.

Thanks,
- Isaac K.

Viewing all articles
Browse latest Browse all 27033

Trending Articles