【问题标题】:Threading.Timer application is consuming more than 50% of CPU, why?Threading.Timer 应用程序消耗超过 50% 的 CPU,为什么?
【发布时间】:2011-03-02 19:59:03
【问题描述】:

我在 VB.net 中编写了以下控制台应用程序。

我的目的是编写一个每分钟触发一次并执行某些任务的应用程序。但是

当我运行这个应用程序时,它消耗了 50% 的 CPU。

我怎样才能让它消耗更少的CPU?

我是否在正确的位置调用计时器(在 main 方法中)?

稍后我想创建一个具有相同任务的 Windows 服务并安装在服务器上。

如何让应用程序消耗更少的 CPU?

Module Module1

    Dim inputPath As String = "C:\Input"
    Dim outputPath As String = "C:\Output"
    Dim folder As Directory

    Sub Main()
        Dim tmr As Timer = New Timer(New TimerCallback(AddressOf Upload), Nothing, 1000, 60000)
        While Not tmr Is Nothing
        End While

    End Sub

    Public Sub Upload(ByVal o As Object)
        Dim sr As StreamReader
        Dim conStr1 As String = "Data Source=TNS Name;User ID=xx; Password=xx;"
        'Look up for pending requests in RQST_TBL
        Dim cnn1 As New OracleConnection(conStr1)
        Dim datReader As OracleDataReader
        Dim cmd1 As New OracleCommand
        cnn1.Open()
        .....
        .....
    End Sub

End Module

谢谢你..

【问题讨论】:

    标签: vb.net windows-services console-application visual-studio-2003 timertask


    【解决方案1】:

    我猜你有两个 CPU?无限的while循环消耗了100%的CPU;使您的 CPU 消耗总量减少 50%。

    从您的代码的外观 - 循环是完全不需要的。您的计时器类将在完成后调用 Upload() 方法。

    删除while循环...

    While Not tmr Is Nothing 
    End While
    

    并使用 Console.Readline 之类的东西来防止应用程序关闭。

    如果你真的喜欢循环,也可以在 while 循环中添加一个 thread.sleep() 调用。

    【讨论】:

    • 谢谢。我这样做了,它不会给 CPU 带来任何负担。
    【解决方案2】:
    While Not tmr Is Nothing
    End While
    

    您已经在上一个问题中被警告过。删除该代码。

    【讨论】:

    • 我在 while 循环中添加了 Thread.Sleep(60000),它几乎占用了 0% 的 CPU。非常感谢。很抱歉我错过了之前的警告..
    【解决方案3】:
    While Not tmr Is Nothing
    End While
    

    这只是一个无限循环。你实际上并没有允许任何事情完成。

    由于这是一个控制台应用程序,您可能只需要一个循环休眠一分钟,然后执行您的任务。

    【讨论】:

      【解决方案4】:

      正如 Rob 所说,50% 的负载可能意味着您正在使用 100% 的 CPU 内核之一。

      您可以使用Console.ReadLine() 代替无限循环来保持控制台应用程序运行。

      在控制台等待输入时,您的计时器仍会按您的预期工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-21
        • 1970-01-01
        • 2010-10-24
        • 2013-12-26
        • 1970-01-01
        • 2019-06-19
        • 2016-04-03
        相关资源
        最近更新 更多