缓慢显示/绘制对话与列表框

本文关键字:列表 对话 绘制 显示 缓慢 | 更新日期: 2023-09-27 17:53:40

我的应用程序使用实体框架来拉入一小部分结果…大约需要3秒钟?为什么会这样呢?

Start.cs

...
private void projectToolStripMenuItem_Click(object sender, System.EventArgs e)
{
    NewProject newProjectForm = new NewProject();
    newProjectForm.ShowDialog(); // It seems to take about 3 or 4 seconds to actually get to this :S
}
...

NewProject.cs

public partial class NewProject : Form
{
    private EFProjectTypeRepository projectTypeRepository;
    public NewProject()
    {
        projectTypeRepository = new EFProjectTypeRepository();
        InitializeComponent();
        ListBoxProjectTypes();
    }
    public void ListBoxProjectTypes()
    {    
        DateTime then = DateTime.Now;
        // PreLoadedResources.projectTypes is a preloaded resource which takes split seconds to load.
        ListBoxProjectType.Items.AddRange(PreLoadedResources.projectTypes.Select(item => (object)item.Title).ToArray()); // If I comment this line out, the dialogue is almost instant @ timeTaken  {00:00:00.0010019}
        DateTime now = DateTime.Now;
        TimeSpan timeTaken = now.Subtract(then); 
    }
}

:

timeTaken   {00:00:02.4261369}  System.TimeSpan

当我第二次显示对话时,它是即时的!

我的列表框到目前为止显示了一个项目lol.

指出

:

public static class PreLoadedResources
{
    public static IEnumerable<ProjectType> projectTypes;
}

缓慢显示/绘制对话与列表框

每次添加项目时,ListBox都必须重新绘制。您可以使用Dmitry使用AddRange()的方法,或者您可以使用BeginUpdate()/EndUpdate()调用来包装您的循环。

ListBoxProjectType.BeginUpdate();
foreach( var projectType in projectTypes )
{
    ListBoxProjectType.Items.Add(projectType.Title);
}
ListBoxProjectType.EndUpdate();

尝试用AddRange:

代替添加单个项目到listbox
public void ListBoxProjectTypes()
{
    IEnumerable<ProjectType> projectTypes = projectTypeRepository.ProjectTypes;
    ListBoxProjectType.Items.AddRange(projectTypes.Select(item => (object)item.Title).ToArray());
}

或者直接用ListBoxProjectType.BeginUpdateListBoxProjectType.EndUpdate换行。

将IEnumerable更改为IList会产生影响:

public static class PreLoadedResources
{
    public static IEnumerable<ProjectType> projectTypes;
}

public static class PreLoadedResources
{
    public static IList<ProjectType> projectTypes;
}

然后在我的加载(这需要2秒命中),我只是.ToList它代替…但是现在showdialog过程只需要几秒钟的时间。