Hack Forums
[C#] Add To ListView From Another Thread [C#] - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] Add To ListView From Another Thread [C#] (/showthread.php?tid=5902618)



Add To ListView From Another Thread [C#] - FarosMoloko - Nov 2, 2018

Quick question.

Whenever I loop through a bunch of images, and add them to my listview control from a thread with:

PHP Code

<?php 
Invoke
(new Action() => { lvPics.Add()... }; 

It completely freezes the UI for 3-5 seconds. This is because invoking code means running it on the UI thread (I think).

So how would I get around this and add them without freezing the UI thread, and keeping it responsive?

Thanks  🤝


RE: Add To ListView From Another Thread [C#] - debug - Nov 2, 2018

You are correct about it freezing because you are running the code on the UI thread. So to get around it, add your add code to to a new thread:

Code
Thread populateList = new Thread(() -> {
     Invoke(new Action() => { lvPics.Add()... };
});
populateList.IsBackground = true;
populateList.SetApartmentState(ApartmentState.STA);
populateList.Start();

Alternatively, you could use a background worker to do the work.


RE: Add To ListView From Another Thread [C#] - sdk - Nov 2, 2018

Try this
PHP Code

<?php 
this
.Invoke(new Action(() => lvPics.Add(image))); 



RE: Add To ListView From Another Thread [C#] - FarosMoloko - Nov 2, 2018

(Nov 2, 2018 09:41 AM)debug Wrote:  You are correct about it freezing because you are running the code on the UI thread. So to get around it, add your add code to to a new thread:

Code
Thread populateList = new Thread(() -> {
    Invoke(new Action() => { lvPics.Add()... };
});
populateList.IsBackground = true;
populateList.SetApartmentState(ApartmentState.STA);
populateList.Start();

Alternatively, you could use a background worker to do the work.

Fantastic. Is there a way to do this with a Task, as its where im currently calling the invoke.

Thanks!


RE: Add To ListView From Another Thread [C#] - He B TeMy - Nov 2, 2018

Using a task the only guaranteed way afaik is this https://stackoverflow.com/a/15957165
Because a task will use the threadpool threads, it won't create new threads.