How to decrease CPU usage when using multiple threads?

I am using vb.net , .NetFramework 2.0 . 
My application gets live stock prices from google and updates stocks in database each 10 seconds.
I get this code for  multithreading. When application starts updating stocks in database(about 200 stocks) , the update takes up to 3 seconds but it increase CPU usage from 10 % to 70 % or 80 %.
What is the best way to to update database without getting CPU increase to high level?
I observed that all threads works at the same time. how to make each thread wait until the second ends?
This is my code. The problem is in function updateThreaded2().
Please I need quick help. Thanks
Public Function Update2(ByVal l As SortableBindingList(Of NewStockList)) As Long
res = 0
UThread = New System.Threading.Thread(AddressOf UpdateThreaded2)
If Me.URunning = True Then
Else
Try
Me.URunning = True
Interlocked.Exchange(Me.UCount, 0) 'threadsafe method of assigning static value
Interlocked.Exchange(Me.UDone, 0) 'threadsafe method of assigning static value
UThread.Priority = Threading.ThreadPriority.BelowNormal
UThread.IsBackground = True
UThread.Start(l)
Return 0
Catch ex As Exception
End Try
End If
End Function
Private Sub UpdateThreaded2(ByVal l As SortableBindingList(Of NewStockList))
Dim i As Integer = 0
Dim threadcount As Integer = Math.Min(Me.MaxThreads, Me.Stocks.Count)
Dim threads(threadcount - 1) As SUTC
Try
While i < Me.Stocks.Count
For j As Integer = 0 To threadcount - 1
If threads(j) Is Nothing Then
If i < Me.Stocks.Count Then
threads(j) = New SUTC(Me.Stocks(i), Me.DefaultService, AdjustSplits, Use20Minutes, l)
threads(j).Thread.Priority = Threading.ThreadPriority.BelowNormal
threads(j).Thread.IsBackground = True
threads(j).Thread.Start()
i += 1
End If
ElseIf threads(j).UpdateState = 0 Then
If i < Me.Stocks.Count Then
SecUpd(j) = Me.Stocks(i).symbol
threads(j) = New SUTC(Me.Stocks(i), Me.DefaultService, AdjustSplits, Use20Minutes, l)
threads(j).Thread.Priority = Threading.ThreadPriority.BelowNormal
threads(j).Thread.IsBackground = True
threads(j).Thread.Start()
i += 1
End If
End If
Next
Dim running As Boolean = True
While running
For j As Integer = 0 To threadcount - 1
If threads(j).UpdateState = 0 Then
Thread.Sleep(10)
running = False
SecUpd(j) = ""
Interlocked.Increment(UDone) 'threadsafe method of incrementing a variable by 1
Interlocked.Exchange(UCount, UCount + threads(j).UpdateCount) 'Threadsafe method for assigning a value
End If
Next
End While
End While
Dim pending As Integer = threadcount
Dim tempcount As Integer = 0
Dim oldcount As Integer = UCount
While pending > 0
pending = threadcount
tempcount = 0
For i = 0 To threadcount - 1
If threads(i).UpdateState = 0 Then
SecUpd(i) = ""
pending -= 1
tempcount += threads(i).UpdateCount
Thread.Sleep(10)
End If
Next
Interlocked.Exchange(UDone, Me.Stocks.Count - pending) 'Threadsafe method for assigning a value
Interlocked.Exchange(UCount, oldcount + tempcount) 'Threadsafe method for assigning a value
End While
Me.URunning = False
Catch ex As System.Threading.ThreadAbortException 'handle abort correctly
Dim pending As Integer = threadcount
Dim tempcount As Integer = 0
Dim oldcount As Integer = UCount
While pending > 0
pending = threadcount
tempcount = 0
For i = 0 To threadcount - 1
If threads(i).UpdateState = 0 Then
SecUpd(i) = ""
pending -= 1
tempcount += threads(i).UpdateCount
End If
Next
Interlocked.Exchange(UDone, Me.Stocks.Count - pending) 'Threadsafe method for assigning a value
Interlocked.Exchange(UCount, oldcount + tempcount) 'Threadsafe method for assigning a value
End While
End Try
End Sub

When the market is opened, stock prices changed every 500 ms . You can see this change on google finance.
I figured as much, but my thoughts are that if you can somehow find a way to make your program more event driven, then it may be possible to reduce unnecessary looping...
“If you want something you've never had, you need to do something you've never done.”
Don't forget to mark
helpful posts and answers
! Answer an interesting question? Write a
new article
about it! My Articles
*This post does not reflect the opinion of Microsoft, or its employees.

Similar Messages

  • Server 2012 R2 100% cpu usage when using search

    Hi all!
    We are experiencing issues with the built in search in WS 2012R2 (Win+Q). Upon starting to type, the explorer.exe process peaks and stays at 100% until typing is done and the search is complete. It also can't keep up with typing and hangs after
    a few keystrokes. We have done tests on 2012 R2, 2012 and 2008 R2 running as VMs with 1 cpu. The tests performed have been run on a host running only the test VM with underlying 2x8 core cpus, SSD, SAN storage and 256GB RAM. Also, we have tested
    both Hyper-V and VMware ESXi 5.0. We see that if we add another CPU to the guest it alleviates the keystroke lagging, but the explorer.exe still consumes 100% cpu.
    When the same tests are run on a physical machine (approx. same specs as the virtualization hosts) the cpu usage reaches 15-20% on one of the physical sockets (numa node). Totally negligible, but still a high number.
    We are afraid of service impact and are keen to know if anyone else is experiencing the same? Maybe someone has a fix?

    Hi TrondWH,
    Thanks for contacting Microsoft.
    Currently, would you please try cleaning boot the server and test how the issue goes. Cleaning boot can exclude some third-party application affect. Following are the detailed steps about clean boot:
    Log on to the computer by using an account that has administrator rights.
    Click Start, type msconfig.exe in the Start Search box, and then press ENTER to start the
         System Configuration Utility.
    On the General tab, click Selective Startup, and then click to clear the Load startup items check box. (The Use Original Boot.ini check box is unavailable.)
    On the Services tab, click to select the Hide all Microsoft services check box, and then click Disable all.
    Click OK, Choose Don’t show this message again and then click Restart.
    Please check if the issue is still the same.
    Please let me know the result.
    Best regards,
    Sophia Sun
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • High cpu usage when using flash player

    Hi,
    Just updated to Mavericks and now I'm having very high cpu usage while watching streams using flash player. CPU usage is somewhere around 110% and after a moment the stream starts to lag and fps is slowing down. I also tried using Chrome but with no difference. Flash player is the newest version 11.9.900.117.
    Any ideas on how to fix this?

    i think its the best to hit the report a problem button in safari, since its appears since i updated safari to 5.1.4! maybe they make a additional update

  • Kernel_task high cpu usage when using external monitor at 1080p

    Specs
    Model Name:          MacBook Pro
      Model Identifier:          MacBookPro6,2
      Processor Name:          Intel Core i7
      Processor Speed:          2.66 GHz
      Number Of Processors:          1
      Total Number Of Cores:          2
      L2 Cache (per core):          256 KB
      L3 Cache:          4 MB
      Memory:          4 GB
      Processor Interconnect Speed:          4.8 GT/s
      Boot ROM Version:          MBP61.0057.B0C
      SMC Version (system):          1.58f15
    My external display is a Samsung PX2370 connected to my MBP using an HDMI cable with a HDMI-to-miniDP adapter
    I first noticed this after the last EFI update several months back. At first I thought kernel_task eats up too much cpu cycles whenever an external display is attached, but it turns out this only happens when the external display is set to 1080p. When external display is set to 720p, kernel_task is pretty much normal (~5% cpu usage) but rises up to ~150% cpu usage once the external display is set to 1080p.
    kernel_task cpu usage is also with normal range when my MBP is connected to a Samsung LCD TV at 720p.
    Anyone having the same problem or know of any fix/workarounds?

    Seems like the problem persists when playing a 720p video on the external display set to 720p. To sum it up
    Video Resolution
    Main Display
    External  (1280x720)
    External (1920x1080)
    480p
    ok
    fluctuating kernel_task cpu usage (~5 to ~150 cpu usage)
    high kernel_task cpu usage
    720p
    ok
    high kernel_task cpu usage
    high kernel_task cpu usage
    1080p
    ok
    high kernel_task cpu usage
    high kernel_task cpu usage

  • How to reduce CPU usage when working in Logic Pro and Kontakt5

    Hello All,
    I have a MacBook Pro 15" early 2011 2.0 GHZ. My main acitivity is making music with my macbook pro. I am using Logic Pro 9 in combination with Kontakt 5.
    I want to get some suggestions in the setup so I can reduce the usage of the CPU. By the way I have upgraded my system with a SSD 256GB , 16GB RAM and have removed the optical drive and installed the the previous factory set HD in the optical bay. I have placed the samples of the Kontakt 5 in the HD so I have enough space on my SSD to run the progrmas fast and smooth !
    If possible give your advise on an optimum setup such as reachanaling the sounds through BUS to AUX channels and other methods in order to reduce the CPU usage. You may even post some good links where I can find more info.
    Thanks in advance
    Wkrgds, Levon

    welshwiggle wrote:
    So Center of Pan,
    If you were to run something like Omnipshere on an active SI track do you get anywhere near the "1 core CPU" spike I'm getting on my Late 2011 TOTR MBP?
    I still dont really get why L9 on a new MBP peforms worse than eg your PC.
    Older versions of Logic (ie: 5.5) don't see individual cores, there is one disk meter and one CPU meter. In some ways it's a more efficient system. This is running on WinXP which happens to be a very good system for audio. Consider this, XP can be installed and take up only half a gig of disk space and do 90% of what most operating systems can do today. 
    I do see single core spikes on my single processor quad core Mac Pro.  There's no way to get around a processor intensive plugin on a single track. A channel strip is tied to a single process (core). I stopped upgrading at 10.6.8 and Logic 9.1.3, because it works. I still get the occasional single core use even with multiple plugs and tracks but I can usually break the logjam by quickly starting and stopping Logic 2 or 3 times.
    I will not upgrade Mac hardware or software unless the next version of Logic is outstanding, I'm fine where I'm at for the next year or two. I enjoy recording performers more than anything else so al I really need is a good sounding, solid system.

  • [SOLVED] qemu-kvm high cpu usage when using pulseaudio alsa-plugin

    My Arch system is configured to use pulseaudio. When an application connects to the sound server it will use either a native pulseaudio driver, or the pulseaudio alsa-plugin if it using a alsa driver.
    qemu-kvm in 'extra' is not compiled with native pulseaudio support. When running guests with sound hardware support, qemu-kvm connects to the sound server using the pulseaudio alsa-plugin.
    The problem I'm seeing is high cpu usage on the Arch host even though cpu usage on the guest is low. Also, the guest is often unresponsive for a period of time when opening sound applications like the mixer or playing audio.
    My solution is to recompile qemu-kvm with native pulseaudio support. This eliminates the use of the pulseaudio alsa-plugin on the Arch host and fixes the above problems.
    An easy was to do this is run:
    yaourt -S qemu-kvm --build
    And edit the PKGBUILD changing the line:
    --audio-drv-list=alsa,sdl,oss,esd \
    To:
    --audio-drv-list=pa,alsa,sdl,oss,esd \
    Finish building and install. Don't forget to add yourself to the kvm group.
    Last edited by bytesize (2010-08-16 02:34:08)

    Problem disappeared.
    I'm not sure, but i think installing xf86-video-modesetting helped to fix this issue.
    I had an error messages in /var/log/Xorg.0.log like this:
    (EE) Failed to load module "modesetting" (module does not exist, 0)

  • High CPU usage when using flash

    Hi, on my laptop I have chrome installed and use it as my browser, when ever i use it to view pages it works fine, when i go on Youtube and watch a video within 5 mins it gets very slow, cpu usage goes to 100% and stays there untill i close the browser. i never had this problem before untill this week, i scaned for viruses and nothing showed up, and i dont used intence programs.I changed hardware accelerations thing and it did nothing.
    Processor: 1st gen intel i3
    Windows 7
    Newest Flash Version

    i think its the best to hit the report a problem button in safari, since its appears since i updated safari to 5.1.4! maybe they make a additional update

  • High cpu usage when handling multiple rtmfp direct connections?

    I'm writing a realtime multiplayer game with adobe AIR and RTMFP. The game uses a server client architecture in which all players are directly connected to a single computer ( host has one output netstream and one input netstream for each player). The problem is that the cpu usage will increase dramatically with the number of connections. 20 players is enough to bring my cpu down to it's knees.
    I've made an experiment replacing RTMFP with TCP sockets ( Using AIR ServerSocket for the host ), with this the game handled 20 connections while using only 2% cpu. Unfortunately TCP sockets create a lot of extra lag because of nagle's algorithm so I can't use them as a replacement of RTMFP, but this experiment almost definitely proves that the bottleneck is in the usage of RTMFP NetStreams.
    Is such high cpu requirements expeceted? If so, what makes it so cpu intensive? Is there anything I can do to lower the cpu usage?
    Some extra data about my game:
    I'm not using NetGroups.
    The host will send about 15 small messages per second to all clients, all messages target the same method called "msg" and use ByteArray as argument. ( myNetStream.send( "msg", msgByteArrayData ); )
    A single game with 20 players is too much for my pc, but 3 game instances with 10 players would still run fine ( although still somewhat high cpu usage )
    Thanks in advance for any help you could provide.

    I just did a couple of net stream connection tests. It appears that the CPU load increase quadratically with the number of connections.
    I also attached the summary for all the results in .png format as attaching the pdf format is not supported.

  • Reduce CPU Usage when Runnig Telnet on Win2000

    Does any one knows how to reduce CPU usage when iam running my telnet developed using java classes.Every time when i start Telnet CPU usage is shooting to 100%.Can any one help to me solve my problem.

    You are probably doing some kind of loop that is eating all the CPU idle time. You could reduce your use of the CPU by calling Thread.yield() when you do not need to do anything for a bit, or even better, Thread.sleep(...) to pause your program for a specified number of milliseconds.
    Hope this helps some.

  • High CPU usage when downloading Files

    Hi there,
    i noticed somethign strage when I download file off the internet or intranet. As soon as my download speed surpasses 1MB/s the CPU usage increases. To be exact the process kernel_task.
    For example:
    2,5 MB/s -> ~30%
    10 MB/s -> ~60-70%
    10+ MB/s -> ~80%
    This is really annoying and I have now clue how to fix this. The Harddrive is a SAMSUNG HM320JI with a Journaled HFS+ partition. No Virus Scanner or anything. Also just reinstalled Snow Leopard yesterday.
    Hope someone can give me some useful information how to fix this.

    Hiya,
    could it have something to do with the write speed/ cache/ram? On a "slow" disk, or one that is nearly full or one that is partitioned, it will take a great deal more ram and cache to "digest" the faster download and write it onto disk. I tend to do downloads to a separate drive. Have you got one? and can you repeat the high CPU usage when downloading / saving to the external drive? I note your drive might have 5,400 rpm, with "just" 8mB cache and 320 GB (quite a few SATA's have 7,200 rpm and 32 mB cache).
    NB: If anything, I found SL more efficient, especially on my 4 year old Macbook, which is running much faster and has got more responsive after installation of (full version of) SL.
    Message was edited by: Alexandre

  • High cpu usage when moving application windows

    Hello all,
    I have two machines with arch installed:
    - an eeepc 701 surf/intel gpu(xorg driver) with xfce
    - an amd 3800+ X2/nvidia 8860 gt(proprietary driver) with kdemod3(also checked with xfce4)/arch amd64 installed.
    I noticed that when i move a window of an application(for example konsole, etc..) too fast i get high cpu usage(30-40 %), when checking with htop.
    Is it normal that the X server uses the cpu so much when moving a window??
    EDIT: up to now i tested it in a friends windows machine, and it happens exactly the same, so i guess is normal. It seems i need to be informed better about how X works :-)
    Last edited by mechmg93 (2008-10-15 08:04:10)

    today i switced back my desktop system to debian unstable and tried to see what the difference is concerning this problem.
    I found out that in kde3 the solution to the "problem" is debians kde default configuration about window behaviour.
    Especially the one mentioned below :
    In debian this is not ticked and this has as a result zero cpu usage when windows are moved.
    Last edited by mechmg93 (2008-10-23 18:36:58)

  • High CPU usage when updating or instlling s/w

    When updating Win8 or installing MS Office system slows down and has to run all night to make any progress. Task Manager shows "System" using 49%. "go to process" shows "NT Kernel & System". The system was bought with Win7 and is now double booting both 7 & 8. Win 8 partition has 500 GB.
    This question was solved.
    View Solution.

    Hello @Dan-44,
    Welcome to the HP Forums, I hope you enjoy your experience! To help you get the most out of the HP Forums I would like to direct your attention to the HP Forums Guide First Time Here? Learn How to Post and More.
    I have read your post on how your computer is displaying a high CPU usage when installing updates or other software. I would be happy to assist you in this matter!
    What other programs are in use when these updates take place? How full is your computer's Local Disk hard drive? In the meantime, I recommend following the steps in this document on Resolving Slow System Performance (Windows 8). This should help improve the speed and efficiency of your operating system.
    Please re-post with the results of your troubleshooting, as well as the requested information above. I look forward to your reply!
    Regards
    MechPilot
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the right to say “Thanks” for helping!

  • Google Earth Plugin and LabVIEW: High CPU usage when adding placemarks

    Hi,
    I posted this question on stackoverflow earlier this week but feel it might be better suited to the LabVIEW community specifically so I'm reposting here:
    I'm writing an application which uses the Google Earth Plugin to display events on the globe. Each event is a single point kml placemark with an icon which is a 3kb png file. Placemarks are uploaded to the plugin as they are received by the software. I am experiencing increasing CPU usage with the number of placemarks that are added.
    I have tested displaying a new placemark every second and running until the software running the plugin completely froze (graph attached). The GEPlugin (green trace) stopped responding (i.e. the globe did not respond to the mouse) at around 1200 placemarks added and CPU usage was at ~30%. When the software itself (red trace) froze the plugin was using around 50% CPU and ~3700 placemarks had been added). After the freeze, no new placemarks were added which caused the software to respond (but not the plugin) so I could clear all the placemarks. After the placemarks were cleared from the globe, the CPU usage of the plugin returned to around 5% CPU.
    So what I've seen is that GEPlugin CPU usage increases linearly with each kml placemark added. Is this the expected behaviour/ a normal limitation of the plugin? If not is there a more efficient way of adding many placemarks to the globe?
    I am using GEPlugin version 7.1.1.1580 (API version 1.010) and LabVIEW 12.0f3
    Please see the test results attached. Any input greatly appreciated!
    Original stackoverflow post:
    http://stackoverflow.com/questions/20994323/google-earth-plugin-with-labview-high-cpu-usage-when-add...
    Attachments:
    Performance Log 020114_095115.png ‏82 KB

    Hello,
    I have had a look at your graphs and understood what you are trying to do. To me it seems that as the image gets more complex it gets harde to render which wold likely cause increase in CPU usage resulting in the freeze. I would suggest you try running the program on anoher computer to check on the RAM front of things. If this is a limitation of the GE Plugin then unfortunately I can not do much to help, but if you think this is a problem coming from your LabVIEW code then you can post your code here and I can take a look.

  • High CPU usage when graphics card is put at work

    I have a 13inch Air with 2GB RAM and 256GB  with Windows 7 Ultimate 64bit. All possible updates have been installed.
    I noticed some tearing when trying to move program windows across the screen so I started checking the CPU usage. I saw that it is spiking to 25-35% when moving a window across the screen.When you drag down a window you can see the different copies of the top bar across the screen. Not smooth at all like on a standard PC windows system. Same issue when scrolling through webpages which spikes the cpu
    I also noticed a high cpu usage when playing mkv files 25-30% while on an Atom HTPC i get a lower load playing the same file. The Air should be faster than an atom with a nvidia 9400m when playing video files.
    I already tried updating the nvidia files to the latest version on their site by hacking the driver inf but this did not resolve the issue.
    Has anyone experienced the same or know what could be causing the beavior?
    Many thanks

    Maybe my initial post was not clear so let me add some clarifications.
    I have the problem with Aero disabled
    I have the problem on the Apple site which does not have any flash content.
    I have already hacked the lastest nvidia drivers to get them on my system which did not change anything. Can you provide a link to some other 'supported' beta drivers?
    I am using the new 13 inch air so it has the newer graphics card so I would expect it to be faster than an old HTPC with a 9400m in it. I wasn't stating that my Air had a 9400m.
    It would be great if someone you also do the test to check the cpu load:
    - when playing a 720 mkv
    - when dragging a window across the screen
    Just open task manager and see if the CPU spikes.
    Many thanks!

  • How to solve power error when using USB camera adapter in your camera

    Hello Everyone,
    First of all I wanna say reducing the output of the USB camera adapter from 100mA to 20mA just to save battery life is by far the most incredible adjustment in the history of @)#*$#%*($#!
    I know most of us bought the USB Camera adapter so we can use it as a USB adapter for the Camera (saves us from taking the memory card on and off the camera) but sadly the "Ginues Apple" reduced it to 20mA which decreases the range of cameras and flash drives that will work with it. I use Gopro Hero 3+ black and everytime I plug it with the adapter to my ipad I keep on seeing this @#@$#@ power error. I didn't want to waste the expensive adapter so I tried to look for a micro sd card reader but I don't think 20mA readers still exist.
    Now to solve this problem is very simple add a power source to help that 20mA up, most of the my friends bought a powered port hub but it's not my type because it's bulky, needs an outlet and not portable.
    So I found a better solution on how you can add a power source and still be portable, the answer is power bank or portable charger.
    Things you need:
    Camera
    USB camera adapter (Ginues Apple product)
    Power bank (I'm using 8,400 mAh)
    Dual USB Male to 5 Pin Mini USB Y Cable
    Ipad
    Procedure:
    Camera --- 5 Pin Mini USB ------------------ USB camera adapter ---------- Ipad
                                                   '---------- Power Bank
    Attach you camera to the 5 pin mini usb then the USB1 male to the female apple's USB camera adapter then to the Ipad. = this will show the power error.
    Then attach the USB2 to the power bank/portable charger to power it up.
    your welcome

    yocto yotta wrote: How to charge iPad Air when using the camera connection kit?
    No can do, Skippy!

Maybe you are looking for

  • Help!  Adobe Reader 9 won't open a PDF in a browser window!

    I just "upgraded" to Adobe Reader 9 today, on my Windows XP computer. I run Firefox 3.0.8 as my web browser. Since installing AR 9, I cannot open PDFs inside my browser.  When I try, I get the following error message: "The Adobe Acrobat/Reader that i

  • HT4890 how to move photos from Photo Stream to existing albums

    iCloud sends photos to my iMac and iPad from my iPhone (or from my iMac to my iPhone & iPad) to the Photo Stream folder in Photos in ech device.  I want to move those photos from the Photo Stream folder to individual albums.  Can this be done?  If I

  • DIRECT DEBIT IN CREDIT

    I have my account on line, how do I claim the credit on my account which is paid by direct debit?  I know there is somewhere you can do this but cannot find?

  • Installing the cs3 sdk on a mac

    Hi, I just downloaded the cs3 sdk for mac, but I can't find any install instructions inside. The readme.txt file points to the porting guide for instructions but the porting guide only says: "insall the sdk" and doesn't specify how. So I'd love some

  • Why my mac book running slowly when i see the movie online?

    why my mac book running slowly when i see the movie online? Many time i hv seen tht whn i start it n in few mins it shows me the colored corsor as its working hard....