开发者

C# Application not shutting down correctly (still runnning in memory after form closed)

I have an odd situation where my application process still lingers in memory after my closing down my main form, my Program.cs code is below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.F开发者_StackOverflow社区orms;
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());
        }
    }
}


You should only have one Application.Run to ensure there is only one message loop on current thread and avoid the kind of problem you are describing.


This is usually indicative of a background thread that hasn't terminated.


If the lockfile does not exist, you get a new "main form" running. I guess Form1 is a hidden form when run.


I've solved my situation. Read this article for details.

I put the critical part into an own thread. The thread is set to Thread.IsBackground = True Now DotNet manage to kill this thread on application exit.

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

C# Application not shutting down correctly (still runnning in memory after form closed)

Regards

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜