【问题标题】:C# Application not shutting down correctly (still runnning in memory after form closed)C# 应用程序未正确关闭(表单关闭后仍在内存中运行)
【发布时间】:2011-06-15 22:01:18
【问题描述】:

我有一个奇怪的情况,我的应用程序在我关闭我的主窗体后仍然在内存中徘徊,我的 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());
        }
    }
}

【问题讨论】:

  • 您的应用程序是否创建任何后台工作线程?
  • 我这里也有同样的情况。使用线程。但是一个线程需要一个“Application.IsShuttingDown”属性,但除了 ApplicationExit 事件之外没有,但该类无法在每次调用时添加此事件。

标签: c# .net windows winforms


【解决方案1】:

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

【讨论】:

  • 是的,如果条件合适,看起来您正在运行 2 个表单(尽管代码缩进不佳会掩盖这一点)。这绝对是不标准的。
【解决方案2】:

这通常表示后台线程尚未终止。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      我已经解决了我的情况。阅读this article了解详情。

      我将关键部分放入自己的线程中。线程设置为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
      

      问候

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-03
        • 1970-01-01
        • 2011-04-02
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多