Click here to Skip to main content
15,938,218 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi ,

how to use the infinite loop using threading....

while i am executing below code... it's taking 100 % usage of the CPU...

How i can reduce the CPU usage at-least 50 %

C#
namespace ThreadingIssue
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart ts = new ThreadStart(Test);
            Thread th = new Thread(ts);
            th.IsBackground = true;
            th.Priority = ThreadPriority.Lowest;
            th.Start();

            ts = new ThreadStart(Test1);
            th = new Thread(ts);
            th.IsBackground = true;
            th.Priority = ThreadPriority.Lowest;
            th.Start();

            Console.ReadKey();
        }

        static void Test()
        {
            while (true)
            {

            }
        }

        static void Test1()
        {
            while (true)
            {

            }
        }
    }
}
Posted
Updated 30-Mar-11 22:06pm
v2
Comments
Sergey Alexandrovich Kryukov 31-Mar-11 14:35pm    
Your while (true) loop is called spin-wait. There is no situations where it can be tolerated. Never ever.
--SA

You do not just sleep, you want to sleep on condition. The the answers with sleep won't help you.
You should never ever use spin wait. You should wait using thread synchronization primitives only.

Also, better not touch thread priority. If you do it right, it will not waste any CPU time. Here is how:

You need not sleep, you need to wait for System.Threading.EventWaitHandle.

Thread code is:

C#
MyEventWaitHandle.WaitOne();


Alternatively, you can use WaitOne with a parameter, which is a timeout.

On this call OS switches the thread off and never schedules it back to execution until it is waken up. The thread will spend exactly zero CPU time. The thread can be waken up only be MyEventWaitHandle.Set or Thread.Abort called from the other thread. That's it.

—SA
 
Share this answer
 
v4
Comments
Olivier Levrey 1-Apr-11 3:56am    
This answer is correct and definetly better than using Sleep. Have a 5.
Sergey Alexandrovich Kryukov 1-Apr-11 4:17am    
Thank you, Olivier.
--SA
100% CPU doesn't mean your program is not working properly, it just means it's using all the available CPU.

There is no sense to make your thread slower except to let the other threads be more responsive. But you already did it with ThreadPriority.Lowest. Changing the priority this way is the best way to make your program run as fast as possible and let the other threads responsive (UI and system threads).

Using System.Threading.Thread.Sleep(...) is good to let other threads work as well, but will slow down your own computations dramatically.

You have available CPU: why wouldn't you use it??? Just tell the system "my task is not so important" (as you did) and it will do the rest.

You could even go further and change the Process.PriorityClass if you need to.

------

I read your comments and I think what you are looking for is synchronization. If you access a variable from 2 different threads, you must secure its access with synchronization objects. Have a look to this link for example:
http://www.albahari.com/threading/part2.aspx[^]
 
Share this answer
 
v5
Comments
vijayr 31-Mar-11 4:55am    
Exactly i am agreed with ur point... but the issue is i can't use the sleep method because of the logic which behind in the software
Olivier Levrey 31-Mar-11 4:59am    
I updated my answer.
Sergey Alexandrovich Kryukov 31-Mar-11 14:47pm    
Sorry Olivier, I did not vote this time.
Sleep does not allow to wake up on condition, sleep time is unknown.
I put the ultimate solution in my Answer, please see.
--SA
Olivier Levrey 1-Apr-11 3:53am    
I didn't say Sleep will "wake up on condition", I said "let other threads work". I didn't mean other threads in the application but other threads in the system which is as you known correct. And where did I write the sleep time was known?
Olivier Levrey 1-Apr-11 3:55am    
And by the way I advised OP to use synchronization functions instead of sleep which is exactly what you said in your answer.
Hi , I agree with Dylan, you should add some kind of interval or sleep.

You can still use your code as you please, adding a 10ms wait will not slow down your computations.

Hope this helps.

I used an AutoResetEvent

Regards

Terence

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadingIssue
{
    class Program
    {
        static AutoResetEvent _AREvt;

        static void Main(string[] args)
        {

            _AREvt = new AutoResetEvent(false);

            ThreadStart ts = new ThreadStart(Test);
            Thread th = new Thread(ts);
            th.IsBackground = true;
            th.Priority = ThreadPriority.Lowest;
            th.Start();

            ts = new ThreadStart(Test1);
            th = new Thread(ts);
            th.IsBackground = true;
            th.Priority = ThreadPriority.Lowest;
            th.Start();

            Console.ReadKey();
        }

        static void Test()
        {
            
            while (true)
            {
             
                //do what you need todo
                _AREvt.WaitOne(10, true);

            }
        }

        static void Test1()
        {
            while (true)
            {
             
                //do what you need todo
                _AREvt.WaitOne(10, true);

            }
        }
    }
}
 
Share this answer
 
v2
Comments
vijayr 31-Mar-11 5:07am    
Thanks.. really great idea...
I will implement this logic in my software, will see the impact and how it's working ...
Olivier Levrey 31-Mar-11 5:19am    
There is absolutely not difference with a Sleep(10) statement. And it will slow down your computations. 10 ms is of course not much for one iteration, but what if you have 1 million? You will then make your loop lose 100 seconds... great!
SwitcherSoft 31-Mar-11 5:31am    
Olivier, You need to have some kind of wait, or thread syncing to take the load of your processor. And it might be more than a 100 seconds if windows have to reclaim memory and resources because your application is using too much. Maybe then end-user PC is not meant to run only your application. I do agree that you will lose some processing time.
Sergey Alexandrovich Kryukov 31-Mar-11 14:50pm    
My 4. While loop is totally is redundant. Alternatively you can use WaitOne with timeout.
--SA
Patiwat S 20-Apr-21 9:33am    
Thanks a lot. It's work for me. I spent all day to find the solution.
In these blocks, you're just in a really tight loop that's going to result in very high CPU

C#
while (true)
{
}


You could try putting the thread to sleep for a moment

C#
while (true)
{
    System.Threading.Thread.Sleep(100);
}
 
Share this answer
 
Comments
vijayr 31-Mar-11 4:24am    
thanks for data... but the issue which i facing
eg ., While(true)
{
doing something based on the variable value which keep increment in another loop in the second thread...
}
Dylan Morley 31-Mar-11 4:25am    
OK, please post code that will be in the loop - update your original question.

vijayr 31-Mar-11 4:50am    
static int curSliderPos =0;
static void Test()
{
while (true)
{
//Based on the "curSliderPos" few operation will be there, which can't mention here :-(
}
}

static void Test1()
{
while (true)
{
//getting the video position and assign it in to the variable
curSliderPos = axWindowsmediaplayer.currentposition
}
}
Dylan Morley 31-Mar-11 4:52am    
Sorry, if you can't mention code I can't offer any relevant advice
vijayr 31-Mar-11 4:56am    
Anyway i was given a outline of the logic from the software...
is it not posible...

Thanks
Vijay r

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900