How to manipulate a Windows Forms control from another thread and get return value via Invoke() method


I was working on a Windows Forms project and I had this requirement to basically do some manipulation on a TreeListView on the parent form (MainForm in this case) for which we already had a developed a method and also to get the return value back from it. To make life even easier, we needed to do this from a BackGroundWorker thread in this case. Now, the problem with Windows Forms controls is that they can’t be manipulated apart from the main thread, so I had to look for a work around of some sort. So here’s a little modified snippet of the code for your understanding:-

if (m.treeListView.InvokeRequired)
{
ra= (ReportData?)m.treeListView.Invoke(new Func<ReportData?>(
() => m.CreateDataforReport(“Rpt type”, false)));
//m is the main form’s reference!

}

So what I’ve done is that I passed the main form’s reference to the child form in the constructor and made the TreeListView and the CreateDataforReport public. Notice that I called CreateDataforReport method inside the Func<ReportData?> and not directly. This is what enables you to get the appropriate return value, be it string, integer or any complex type like I have it here.