Program with System.Timers.Timer runned via mono p

2019-08-08 15:03发布

问题:

I've noticed that programs where usage of System.Timers.Timer object appears is very CPU consumptive (almost 100percent for single CPU core).

I'm using Ubuntu 11.10, here is my version of mono:

mono -V
Mono JIT compiler version 2.10.5 (Debian 2.10.5-1)
Copyright (C) 2002-2011 Novell, Inc, Xamarin, Inc and Contributors. www.mono-project.com
        TLS:           __thread
        SIGSEGV:       altstack
        Notifications: epoll
        Architecture:  amd64
        Disabled:      none
        Misc:          softdebug
        LLVM:          supported, not enabled.
        GC:            Included Boehm (with typed GC and Parallel Mark)

Here is sample program, which causes unexpected high CPU usage:

using System;
using System.Timers;

namespace MonoCPUTest
{
    class Program
    {
        static Timer _refresh = new Timer();

        static void Main(string[] args)
        {
            _refresh.Interval = 2000;
            _refresh.AutoReset = true;
            _refresh.Elapsed += (x, y) => refresh();
            _refresh.Start();

            while (true)
            {
                Console.WriteLine("loop");
                System.Threading.Thread.Sleep(10000);
            }
        }
        static void refresh()
        {
            Console.WriteLine("refresh");
        }
    }
}

Thank you very much for any help.

回答1:

I've just tested (by copy pasting, compiling and executing your code) and cannot reproduce the issue, the CPU load is about 0. I'm using newer version of Mono, specifically the one compiled from the git tree couple days ago; so if there was an issue like that, it was fixed.

I guess upgrading your Mono is not possible without external PPA, but this is what should be done here if you are not forced to use this version for some other reason. You can also compile one from the source, which is as easy, as configure, make, make install ;)