[RESOLVED] [02/03] Multithreading CPU Usage
Hi guys,
This is sort of related to this post but I wasn't getting any love and I thought this was probably a better place to ask the question... Its a rather long post so I've divided it up a bit. You probably don't need to read the specifics if you don't want to, but I've included them just in case.
THE BASICS: I have a multithreaded application which runs about three threads other than the main app, which have loops along the lines of "while true... end while." When I run the app the CPU usage immediately jumps up to 100% and even though I have the priority on the threads set to 'Lowest' the main application still runs very slowly - the form doesn't redraw regularly, mouse handling is not responsive etc.
THE SPECIFICS: Its basically a chat program being used to run an MSN whiteboard style app. I think the problem occurs in these sections:
a) where the server is waiting on new connections: (fragment)
VB Code:
localListener = New TcpListener(Dns.Resolve(ipHost).AddressList(0), ipPort)
localListener.Start()
While (localListener.Pending = False)
Thread.Sleep(1000) 'have done this to try and pause the listening thread
End While
tClient = localListener.AcceptTcpClient
b) where both the client and server are waiting for transmissions over the TCP socket. (fragment)
VB Code:
While True
Dim i As Integer = 0
While clientStream.DataAvailable
buffer(i) = clientStream.ReadByte
i += 1
End While
End While
THE QUESTION:
I guess there are two questions
- Firstly is there a way I make these threads take up less of the processing time, for example taking them out into a separate app which I call at run time as a process?
- If this won't fix it, is there a better way to code the loops so that they don't chew up so much CPU time?
Re: [02/03] Multithreading CPU Usage
I have sorted this out - the threading part of this app is still slow, but I have asked each thread to sleep for a second if it is awaiting data
It turns out that the real problem was that I was redrawing my picture box every time the form repainted, and as its quite an expensive operation (I have a few 'layers' which are their own in memory bitmaps) this was taking a stupid amount of time.