如果您在同一线程中执行非 UI 工作(在您的情况下,操作流和图像),您需要期望您的 UI 会变慢。解决方案是将这项工作卸载到另一个线程,将 UI 线程留给用户。一旦工作线程完成,告诉 UI 线程进行更新。
第二点是批量更新 ListView 数据时,你应该告诉 ListView 等到你完成所有操作。
如果你这样做更好。评论是内联的。
// Create a method which will be executed in background thread,
// in order not to block UI
void StartListViewUpdate()
{
// First prepare the data you need to display
List<ListViewItem> newItems = new List<ListViewItem>();
foreach (var dr in Ringscode.Where(S => !S.IsSold))
{
newItems.Insert(0,
new ListViewItem(dr.CodeNo.ToString(), dr.RingID.ToString()));
imgList.Images.Add(dr.RingID.ToString(), binaryToImage(dr.Image));
}
// Tell ListView to execute UpdateListView method on UI thread
// and send needed parameters
listView.BeginInvoke(new UpdateListDelegate(UpdateListView), newItems);
}
// Create delegate definition for methods you need delegates for
public delegate void UpdateListDelegate(List<ListViewItem> newItems);
void UpdateListView(List<ListViewItem> newItems)
{
// Tell ListView not to update until you are finished with updating it's
// data source
listView.BeginUpdate();
// Replace the data
listViewCollection.Clear();
listViewCollection.LargeImageList = imgList;
listViewCollection.LargeImageList.ImageSize = new System.Drawing.Size(100, 100);
foreach (ListViewItem item in newItems)
listViewCollection.Add(item);
// Tell ListView it can now update
listView.EndUpdate();
}
// Somewhere in your code, spin off StartListViewUpdate on another thread
...
ThreadPool.QueueUserWorkItem(new WaitCallback(StartListViewUpdate));
...
当我内联编写此代码时,您可能需要修复一些问题,并且没有在 VS 中对其进行测试。