C#应用程序未正确关闭(在窗体关闭后仍在内存中运行)

3

我遇到了一个奇怪的情况,即在关闭主窗体后,我的应用程序进程仍然停留在内存中。以下是我的Program.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace WindowsFormsApplication1
{
    static class Program
    {    
        [Flags]
        enum MoveFileFlags
        {
            None = 0,
            ReplaceExisting = 1,
            CopyAllowed = 2,
            DelayUntilReboot = 4,
            WriteThrough = 8,
            CreateHardlink = 16,
            FailIfNotTrackable = 32,
        }

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        static extern bool MoveFileEx(
            string lpExistingFileName,
            string lpNewFileName,
            MoveFileFlags dwFlags
        );

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
        string lockFile = "run.dat";
        if (!File.Exists(lockFile))
        {
            // that's a first run after the reboot => create the file
            File.WriteAllText(lockFile, "");

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form2());
        }
        else
        {
            // that's a consecutive run      
        }
          Application.Run(new Form1());
        }
    }
}

你的应用程序是否创建了任何后台工作线程? - John Arlen
我这里也有同样的情况。正在使用线程。但是一个线程需要一个“Application.IsShuttingDown”属性,除了ApplicationExit事件之外没有其他方法可以实现,但是该类无法在每次调用时添加此事件。 - Nasenbaer
4个回答

5

为确保当前线程上只有一个消息循环并避免您所描述的问题,您应该仅有一个Application.Run。


是的,如果条件满足的话,看起来你正在运行2个表单(尽管代码的缩进不好以至于使这一点模糊不清)。这肯定是非标准的。 - spender

2
这通常表明一个后台线程没有终止。

1

我已经解决了我的问题。详情请阅读这篇文章

我将关键部分放入了一个独立的线程中。该线程被设置为 Thread.IsBackground = True。现在,DotNet 能够在应用程序退出时终止此线程。

Dim thStart As New System.Threading.ParameterizedThreadStart(AddressOf UpdateImageInGuiAsync)
Dim th As New System.Threading.Thread(thStart)
th.Start() 
th.IsBackground = True

后台线程 敬礼


1

如果锁定文件不存在,您将获得一个新的“主窗体”运行。我猜Form1在运行时是一个隐藏的窗体。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接