长时间运行计时器增加C#中的私有字节

时间:2016-08-06 11:12:32

标签: c# timer garbage-collection

我创建了一个在后台运行的应用程序,并将4个计时器用于不同的目的。在已经完成的计时器事件上完成任务但内存专用字节正在增长。

我读到了关于Timer类的内容,据说Timers必须在任务完成后处理,但问题是计时器必须在后台运行以完成任务。

class myservice
{

    public void Start()
    {
        Timer tActiveWin = new Timer();
        tActiveWin.Interval = TimeSpan.FromSeconds(2).TotalMilliseconds;
        tActiveWin.Elapsed += TActiveWin_Elapsed;
        tActiveWin.AutoReset = true;
        tActiveWin.Enabled = true;
    }

    private void TActiveWin_Elapsed(object sender, ElapsedEventArgs e)
    {
        var win = new WindowEvents().GetActiveWindow();
        Console.WriteLine(win.activewindowtitle);
    }

    class WindowEvents
    {
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    [DllImport("user32.dll", SetLastError = true)]
    static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

    public JsonAppEvents.Activewindow GetActiveWindow()
    {
        JsonAppEvents.Activewindow activeWin = new JsonAppEvents.Activewindow();

        IntPtr hWnd = GetForegroundWindow();

        int processID = 0;
        int threadID = GetWindowThreadProcessId(hWnd, out processID);


        using (Process p = Process.GetProcessById(processID))
        {
            StringBuilder text = new StringBuilder(256);
            if (GetWindowText(hWnd, text, 256) > 0)
            {
            text.ToString();
            }

            activeWin.activewindowfullpath = p.MainModule.FileName;
            activeWin.activewindowtitle = p.MainWindowTitle;
            activeWin.time = p.StartTime.ToString("ddd, dd MMM yyyy HH:mm:ss");
            activeWin.activewindowdescription = p.MainModule.ModuleName;

            p.Dispose();

            hWnd = IntPtr.Zero;
            processID = 0;
            threadID = 0;
            text.Clear();
            text = null;
        }

        return activeWindow.Result;    
    }


class JsonAppEvents
{
    public class Activewindow
    {
        public string activewindowfullpath { get; set; }
        public string activewindowdescription { get; set; }
        public string time { get; set; }
        public string activewindowtitle { get; set; }
    }
}

我也对垃圾收集工作进行了搜索,因为在C#中我们无法控制何时会占用内存,我对其进行了更多调查。任何线索都会有所帮助。

1 个答案:

答案 0 :(得分:0)

ExoPlayer不同,不安全的句柄不会自动处理。所以 使用SafeFileHandle Win32 API来丢弃不安全的句柄。句柄的大小取决于目标体系结构 - 它是32位或64位。所以声明函数并按如下方式使用它:

CloseHandle()