Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Add To ListView From Another Thread [C#]

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  🤝
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.
Try this
PHP Code

<?php 
this
.Invoke(new Action(() => lvPics.Add(image))); 
Hi
(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!
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.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by Johan CruyffJun 14, 2017 09:41 AM 5 205 Jun 14, 2017 09:41 AM
Last Post: Johan Cruyff
[.NET] by 270zFeb 24, 2016 05:33 PM 7 227 Feb 24, 2016 05:33 PM
Last Post: Ninja
[C#] by Ðr1psApr 8, 2015 05:44 PM 2 89 Apr 8, 2015 05:44 PM
Last Post: Ðr1ps