0
I have loaded many images in a listview using ImageList in c#. When many many images are loaded then it takes a long time. So I call the method in backgroundworker. In the backgroundworker I had to add images to ImageList and add ImageList to ListView. So I have used safeinvoke() method listView1.SafeInvoke(d=>d.Items.Add(item)).
. Everything works fine. Images are displayed one by one in the listview. But the problem is the listview is continuously refreshing when a new item is added. This refreshing seems disturbing to the user. When I have added the item without using background worker (listView1.Items.Add(item)) then it worked fine. It was added one after another smoothly without refreshing. I want to add item without refreshing the listview.
Where is the problem? Is the problem of backgroundworker or the SafeInvoke () method? How to solve it?
sample code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string[] fileNames = Directory.GetFiles(@"E:\Image");
foreach (string flName in fileNames)
{
Bitmap btmap = (Bitmap)Image.FromFile(flName);
scanNo++;
//imageList.Images.Add(newBtmap); when backgroundworker was not used
this.SafeInvoke(d=>d.imageList.Images.Add(newBtmap));
ListViewItem item;
item = new ListViewItem();
item.ImageIndex = scanNo - 1;
item.Text = scanNo.ToString();
// listView1.Items.Add(item); when backgroundworker was not used
listView1.SafeInvoke(d=>d.Items.Add(item));
}
}
http://www.codeproject.com/Articles/52752/Updating-Your-Form-from-Another-Thread-without-Cre?msg=4151406#xx4151406xx
public static TResult SafeInvoke
{
if (isi.InvokeRequired) {
IAsyncResult result = isi.BeginInvoke(call, new object[] { isi });
object endResult = isi.EndInvoke(result); return (TResult)endResult;
}
else
return call(isi);
}
public static void SafeInvoke
{
if (isi.InvokeRequired) isi.BeginInvoke(call, new object[] { isi });
else
call(isi);
}
learner learnerPosted Feb 9, 2012, 1:12 AM
Sam HobbsPosted Feb 8, 2012, 4:39 PM
You say "when a new item is added" and that is somnething you need to clarify. You do not explain how/where the items are being added.
You also do not specify how the data is bound to the control or if it is not bound how the ListView is being filled and updated.
As best as I can understand from your code, you get a list of bitmap files and then put the bitmap from each file into the ListView. If you do all that many times then it makes sense that it requires a lot of processing. If new bitmaps are added as files and therefore the only way to know that there is a new bitmap is to list all the files, then the solution is to monitor the directory to determine that there is a new file and then add just the one bitmap. I am not sure however that that applies to your program; does that sound like what you need?