您的位置:首页 > 编程语言 > C#

C#程序优化的一些体会

2012-05-29 21:07 267 查看
主要针对大数据量的操作,界面响应假死或整体慢速的问题。

1、使用多线程在后台操作数据,应对程序界面假死问题。

Thread thread=new Thread(new ThreadStart(Method));

thread.Start();
2、数据添加到控件显示的速度问题。例如使用ListView,使用控件的VirtualMode模式。以及其他一些直接映射内存数据到控件的方式。

建立缓存

private static List<ListViewItem> cacheit = new List<ListViewItem>();

private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
try
{
e.Item = cacheit[e.ItemIndex];
}
catch (Exception)
{
};
}
线程中:

开始位置

cacheit.Clear();

listView1.VirtualListSize = 0;

然后使劲的插入数据到cacheit中

最后

listview1.VirtualListSize=cacheit.Count;

避免ListView刷背景闪烁的问题

class ListViewNF : System.Windows.Forms.ListView
{
public ListViewNF()
{
// 开启双缓冲
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

// Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}

protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}
3、string 用来做为建立字符串追加的基础时,速度很慢。

例如

string s="";

s+="some"; //反复加到很长的时候速度很慢。。。

需要改用StringBuilder来追加,速度飞一般快。

4、数据库操作,尽量优化SQL查询语句,减少调用次数,好好和数据库用SQL语言沟通,把工作交给数据库去处理吧!!


5、减少反馈进度的操作,如果每个操作都去反馈信息到界面报告进度,会拖慢整体速度,使得在大量数据时降低效率或达几十倍左右。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息