0

I've got a VB.Net application that has two background workers. The first one connects to a device and reads a continuous stream of data from it into a structure. This runs and utilises around 2% of CPU.

From time to time new information comes in that's incomplete so I have another background worker which sits in a loop waiting for a global variable to be anything other than null. This variable is set when I want it to look up the missing information.

When both are running CPU utilisation goes to 30-50% of CPU.

I thought that offloading the lookup to its own thread would be a good move as the lookup process may block (it's querying a url) and this would avoid the first background worker from getting stuck as it needs to read the incoming data in realtime. However, just commenting out the code in worker 2 to leave just the Loop as shown below still results in the same high CPU.

Do While lookupRunning = True
            If lookup <> "" Then

            ' Query a URL and get data
            End If
Loop

The problem is clearly that I'm running an infinite loop on worker 2. Other than dumping this idea and looking up the information on the main thread with a very short timeout in case the web service fails to respond, putting Application.DoEvents in my loop doesn't seem to make much difference and seems to be frowned upon in any case.

Is there are better way to do this ?

Philip Lee
  • 157
  • 3
  • 16
  • Yeah, a busy loop will do that. Without a bit more details, it's a bit hard to say, but I think you would benefit from using the [BlockingCollection](https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx) class. If implemented properly, your 2nd worker would efficiently (no CPU usage) block on the collection while waiting for work to do. – sstan Aug 31 '16 at 23:38
  • You should _**never**_ call `Application.DoEvents()` unless you know 100% what you are doing. `DoEvents()` just allows the application to process paint messages which will make it seem responsive, but will itself increase CPU usage if called continuously. Also calling it in a separate thread/task will most likely create even more problems than what it's already capable of. -- [Here's a great answer from Hans Passant](http://stackoverflow.com/a/5183623/3740093) about `Application.DoEvents()`. – Visual Vincent Aug 31 '16 at 23:42
  • Maybe instead of wait infinite time could come to sleep the current thread with some of time like 500 ms Thread.Sleep(500) in vb6 i worked with a timeout on demand in callback here more details http://stackoverflow.com/a/8639019/552877 – Carlos Cocom Aug 31 '16 at 23:51
  • @sstan I wasn't aware of that class. From what you say it sounds like it may be of use so I'll check it out. Thanks for the suggestion – Philip Lee Sep 01 '16 at 06:48

0 Answers0