Sunday, June 23, 2019

c# - Cross-thread operation not valid











Okay, I know why this is giving me this error:




Cross-thread operation not valid:
Control 'Form1' accessed from a thread
other than the thread it was created

on.




But... How can I make this workable?



System.Threading.Thread t = new System.Threading.Thread(()=>
{
// do really hard work and then...
listView1.Items.Add(lots of items);
lots more UI work

});
t.Start();


I don't care when, or how the Thread finishes, so I don't really care about anything fancy or over complicated atm, unless it'll make things much easier when working with the UI in a new Thread.


Answer



You can't. UI operations must be performed on the owning thread. Period.



What you could do, is create all those items on a child thread, then call Control.Invoke and do your databinding there.




Or use a BackgroundWorker



    BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) => { /* create items */ };
bw.RunWorkerCompleted += (s, e) => { /* databind UI element*/ };

bw.RunWorkerAsync();

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...