[C#] TcpClient problems

Soldato
Joined
12 Apr 2004
Posts
11,788
Location
Somewhere
I have the following code, which simply reads data from a TCP connection with a server:
Code:
private byte[] GetTcpData()
{
	if (m_IsQueryInProgress)
	{
		return m_CachedTcpData;
	}

	m_IsQueryInProgress = true;
	try
	{
		TcpClient client = new TcpClient();
		client.Connect(m_ServerAddress, m_TcpPort);
		client.ReceiveTimeout = Properties.Settings.Default.TcpTimeout;
		client.SendTimeout = Properties.Settings.Default.TcpTimeout;
		[B]int availableData = client.Available;[/B]
		using (Stream stream = client.GetStream())
		{
			BinaryReader reader = new BinaryReader(stream);
			m_CachedTcpData = reader.ReadBytes(availableData);
		}
		return m_CachedTcpData;
	}
	finally
	{
		m_IsQueryInProgress = false;
	}
}

This all works perfectly, and returns 41 bytes of data, if I step through the line typed in bold (a break point must be placed on that line or before, then stepped trough). If I don't, client.Available remains at 41, and availableData at 0.

I'm stumped. Any ideas? :)
 
Well, I don't have any watches on those variables, and I haven't received any data via that TcpClient yet, so I suppose it must be the former. How would I get round this?

Also, I can't find any TcpSocket class in the object browser :confused:
 
Just read through your post Reezer, very helpful! :)

Are there any inherent advantages in doing this specific operation asynchronously? As it happens, the method I posted would be called on a threadpool thread anyway, so response time isn't too much of an issue.
 
UI updating isn't a problem really. The object that the method is a member of is completely independant and self-contained. The main UI thread simply refreshes the data contained in the object with said method (well, another method which calls that method in the process), and then takes the data from the object's properties.

Basically, I have a class called StatusMonitor, with a RefreshInfo() method. This method returns void and simply updates the data contained within the object's fields. It does this by calling two methods (which is where the TCP data is needed) from another class, StatusChecker, on ThreadPool threads (QueueUserWorkItem) which themselves are synchronous, and return the info directly. The callback for QueueUserWorkItem then updates the StatusMonitor object's fields once the methods have returned.

It just wouldn't make a lot of sense to get the TCP data in async as well, as it's already being done async.
 
Last edited:
Back
Top Bottom