线程和CPU使用率100

线程和CPU使用率100

本文介绍了线程和CPU使用率100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何使用线程使用无限循环....

当我执行以下代码时...占用100%的CPU使用率...

我如何将CPU使用率至少降低50%

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 %

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)
            {

            }
        }
    }
}

推荐答案

MyEventWaitHandle.WaitOne();



或者,您可以将WaitOne与参数一起使用,这是超时.

在此调用中,操作系统关闭线程,并且从不将其调度回执行,直到将其唤醒.该线程将完全花费零CPU时间.只能从另一个线程调用MyEventWaitHandle.SetThread.Abort来唤醒该线程.就这样.

—SA



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



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);

            }
        }
    }
}


这篇关于线程和CPU使用率100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:04