I\'m trying to populate a listview from another class, but I\'m geting this error: \" Cross-thread operation not valid: Control \'listView1\' accessed from a thread other than t
A neat trick to avoid duplicate code or malfunction when a function is called both from UI thread and other threads is:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void AddItems( string[] items )
{
if(InvokeRequired)
{
Invoke((MethodInvoker) delegate { this.AddItems(items); });
return;
}
ListViewItem[] range = (items.Select(item => new ListViewItem(item))).ToArray();
listView1.Items.AddRange(range);
}
}
}
The first time the function enters in another thread, invoke is called and the function simply calls itself again, this time in the right thread context. The actual work is then written down only once after the if() block.