ShowDialog内存泄露问题
ShowDialog
显示窗口有show和ShowDialog方法
调用ShowDialog方法显示窗口,
除非手动关闭,否则程序永远不执行ShowDialog往后的代码;
(后面的 Application.OpenForms[k].Close()方法,关闭窗口代码无效,不会执行)
且切换窗口后,内存一直增加
int i = 0;
while (true)
{
if (i < Application.OpenForms.Count)
{
Application.OpenForms[i].Hide();//隐藏窗口
i++;
}
else
{
break;
}
}
//反射创建窗口实例
Form helloWorld = (Form)Activator.CreateInstance("WindowsFormsApp1", "WindowsFormsApp1." + openForm).Unwrap();
//显示窗口
helloWorld.ShowDialog();
int k = 0;
while (true)
{
if (k < Application.OpenForms.Count)
{
Application.OpenForms[k].Close();//关闭窗口
k++;
}
else
{
break;
}
}
解决方案
1.可以定义一个全局窗口来控制窗口的跳转,这个方法很麻烦,且后期占用内存;
2.目前使用委托+异步+反射来实现
新建一个类,专门用来放委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
namespace WindowsFormsApp1
{
class DelegateForm
{
public delegate void DoWorkHandler(string openForm);
public DoWorkHandler handlerF2 = (openForm) =>
{
FormCollection collection1 = Application.OpenForms;
Task.Factory.StartNew(() => {
int i = 0;
while (true)
{
if (i < Application.OpenForms.Count)
{
Application.OpenForms[i].Hide();
i++;
}
else
{
break;
}
}
});
Task.Run(() => {
Form helloWorld = (Form)Activator.CreateInstance("WindowsFormsApp1", "WindowsFormsApp1." + openForm).Unwrap();
helloWorld.ShowDialog();
});
};
}
}
跳转的窗口
直接创建实例然后调用 handlerF2(“Form2”) 方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static WindowsFormsApp1.DelegateForm;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
// 创建委托实例
DelegateForm nc1 = new DelegateForm();
//参数一需要打开的窗口
nc1.handlerF2("Form2");
}
}
}
切换按钮,内存增加到一定值后保持不变
大神们有更好的方法解决ShowDialog方法内存泄露的问题,请下方留言