长时间运行定时器增加c#中的私有字节
本文关键字:字节 运行 定时器 增加 长时间 | 更新日期: 2023-09-27 18:01:16
我创建了一个在后台运行的应用程序,并为不同的目的使用了4个定时器。在计时器经过的事件中,任务完成,但内存私有字节正在增长。
我读了关于Timer类的文章,据说Timer必须在任务完成后被处理,但问题是Timer必须在后台运行以完成任务。
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#中我们不能控制何时内存将被声明,我坚持更多的发现。任何线索都会有帮助的
与SafeFileHandle
不同,不安全句柄不会自动处理。所以使用CloseHandle()
Win32 API丢弃不安全句柄。句柄的大小取决于目标体系结构——它是32位还是64位。因此,声明函数并按如下方式使用它:
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern bool CloseHandle([In] IntPtr Handle);
.
.
.
IntPtr hWnd = GetForegroundWindow();
.
.
.
CloseHandle(hWnd);