2012-08-04 71 views
0

我正在使用下面的函數來添加items.this函數工作正常,但它需要很多時間執行。請幫助我減少項目添加在列表視圖中的執行時間。我可以減少listview的執行時間嗎?

功能:

listViewCollection.Clear(); 
listViewCollection.LargeImageList = imgList; 
listViewCollection.LargeImageList.ImageSize = new System.Drawing.Size(100, 100); 
foreach (var dr in Ringscode.Where(S => !S.IsSold)) 
{ 
    listViewCollection.Items.Insert(0, 
        new ListViewItem(dr.CodeNo.ToString(), dr.RingID.ToString())); 
    imgList.Images.Add(dr.RingID.ToString(), binaryToImage(dr.Image)); 
} 

public Image binaryToImage(System.Data.Linq.Binary binary) 
{ 
    byte[] b = binary.ToArray(); 
    MemoryStream ms = new MemoryStream(b); 
    Image img = Image.FromStream(ms); 
    return img; 
} 
+0

我想耗時的方法是'binaryToImage',你還沒有分享。 – yogi 2012-08-04 11:27:45

+0

public Image binaryToImage(System.Data.Linq.Binary binary) byte [] b = binary.ToArray(); MemoryStream ms = new MemoryStream(b); 圖片img = Image.FromStream(ms); return img; } – Tulsi 2012-08-04 11:28:59

+0

@yogi binaryToImage return image – Tulsi 2012-08-04 11:29:55

回答

1

你需要想到的是你的UI是怎麼回事,如果你做同樣的 線程nonUI工作(在你的情況下,操作流和圖像)是緩慢的。解決方案是將這項工作卸載到另一個線程,將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中測試它。