开发者

Strange Process.GetProcesses problem

开发者 https://www.devze.com 2023-04-06 17:09 出处:网络
This code behaves strangely. If I comment the line Process[] processlist = Process.GetProcesses(); then it works as expected. I see a \'test\' message every 2 seconds. If I leave this line, it will

This code behaves strangely. If I comment the line

        Process[] processlist = Process.GetProcesses();

then it works as expected. I see a 'test' message every 2 seconds. If I leave this line, it will print 2-3 'test' messages then s开发者_开发问答top. What am I doing wrong?

static void processTimerCallback(object x)
    {
        try
        {
            Process[] processlist = Process.GetProcesses();
        }
        catch
        {
        }
        Console.WriteLine("test");
    }

static void Main(string[] args)
{
    System.Threading.Timer processTimer = new System.Threading.Timer(new   TimerCallback(processTimerCallback), null, 2000, 2000);
    Application.Run(form = new MainForm());
}


I linked to another answer that explains the problem. In a nutshell, the problem is not with the Process class, it is with the timer. It is a local variable of your Main() method, not sufficient to keep the garbage collector convinced that the timer object is still in use. Nobody can repro the problem from your code snippet because the garbage collector won't run often enough.

The difference between the Debug and Release build is the way the jitter reports the life-time of local variables. When a debugger is attached, it reports it life for the entire method body. That makes debugging easy.

Two basic fixes for this problem. The insight one:

static void Main(string[] args)
{
    System.Threading.Timer processTimer = new System.Threading.Timer(new   TimerCallback(processTimerCallback), null, 2000, 2000);
    Application.Run(form = new MainForm());
    GC.KeepAlive(processTimer);
}

And the practical one:

static System.Threading.Timer processTimer;

static void Main(string[] args)
{
    processTimer = new System.Threading.Timer(new   TimerCallback(processTimerCallback), null, 2000, 2000);
    Application.Run(form = new MainForm());
}


I tried the program once as a console app and once as a windows forms app. It didn't crash on my machine, but I'm logged in as an administrator. Maybe you access a process you are not allowed to?

The code is a bit strange because you access the Console within a windows application. And I miss the attribute STAThread before the Main method (however I tried without, it didn't crash).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号