【发布时间】:2013-05-18 19:45:28
【问题描述】:
我有一种在 Internet Explorer 中打开 URL 的方法。如果已经打开了 Internet Explorer,它应该在新选项卡中打开。如果没有,则应打开一个新的 Internet Explorer。
我的代码:
public static void OpenURL(string Url)
{
bool already_navigated = false;
ShellWindows instances = new ShellWindows();
//Check if there is an Internet Explorer
if (instances.Count > 0)
{
foreach (InternetExplorer ie in instances)
{
if (ie.Name == "Windows Internet Explorer")
{
if (!already_navigated)
{
//Navigate and open in New Tab
already_navigated = true;
ie.Navigate(Url, 0x10000);
//Bring window to front
IntPtr hwnd = (IntPtr)ie.HWND;
WindowHandler.Window w = new WindowHandler.Window(hwnd, "Internet Explorer");
w.Minimize();
w.Restore();
}
}
}
}
//No internet explorer found!
if (!already_navigated)
{
//Start new Internet Explorer
Process proc = Process.Start("IExplore.exe", Url);
}
}
这很好用!但是当我调用这段代码时,我的内存会无限循环增加,直到我得到一个 OutOfMemoryException...
经过反复试验,我发现这段代码抛出了异常:
public static void OpenURL(string Url)
{
bool already_navigated = false;
ShellWindows instances = new ShellWindows();
/*
//Check if there is an Internet Explorer
if (instances.Count > 0)
{
foreach (InternetExplorer ie in instances)
{
if (ie.Name == "Windows Internet Explorer")
{
if (!already_navigated)
{
//Navigate and open in New Tab
already_navigated = true;
ie.Navigate(Url, 0x10000);
//Bring window to front
IntPtr hwnd = (IntPtr)ie.HWND;
WindowHandler.Window w = new WindowHandler.Window(hwnd, "Internet Explorer");
w.Minimize();
w.Restore();
}
}
}
}
//No internet explorer found!
if (!already_navigated)
{
//Start new Internet Explorer
Process proc = Process.Start("IExplore.exe", Url);
}*/
}
而这段代码不会:
public static void OpenURL(string Url)
{
bool already_navigated = false;
/*
ShellWindows instances = new ShellWindows();
//Check if there is an Internet Explorer
if (instances.Count > 0)
{
foreach (InternetExplorer ie in instances)
{
if (ie.Name == "Windows Internet Explorer")
{
if (!already_navigated)
{
//Navigate and open in New Tab
already_navigated = true;
ie.Navigate(Url, 0x10000);
//Bring window to front
IntPtr hwnd = (IntPtr)ie.HWND;
WindowHandler.Window w = new WindowHandler.Window(hwnd, "Internet Explorer");
w.Minimize();
w.Restore();
}
}
}
}*/
//No internet explorer found!
if (!already_navigated)
{
//Start new Internet Explorer
Process proc = Process.Start("IExplore.exe", Url);
}
}
我只有一个结论,问题在于:
ShellWindows instances = new ShellWindows();
但经过一番谷歌搜索,我找不到任何有类似问题的人。所以我不确定我是否做错了什么,或者我对这个问题是否正确。
有人知道怎么回事吗?
【问题讨论】:
-
我打赌是内存泄漏。在 C# 中听起来很奇怪,但是是的,你为什么不在不同点打破它,看看哪个喜欢增加内存的使用? Memory Leak is possible
-
@AnnArbor87 我无法真正调试,因为目前我无法在用于开发的机器上测试代码。我只能通过更改代码并观察发生的情况进行调试。
-
尝试注释掉代码的其他部分,例如内部 IF (!already_navigated) 并发布发生的情况
-
我认为你遇到的问题是因为 IE 对象。你关闭实例吗?你想达到什么目标?
-
这并没有什么不同。只有当我删除 ShellWindows 行时,它才不会导致内存泄漏。
标签: c# memory-leaks out-of-memory