I've been googling around and trying some different approaches but none of them is working.
Using an anti-cross-thread function to return a value
C# Return value from function invoked in thread
http://www.dreamincode.net/forums/topic/188209-cross-thread-calls-made-easy/
My code (very briefly) is the following:
public partial class print : Form {
ListView _listOfCategories = new ListView();
delegate string getNameOfPrinterCallBack(string name);
private string getNameOfPrinter(string name){
ListViewItem search = new ListViewItem();
if (this._listOfCategories.InvokeRequired)
{
getNameOfPrinterCallBack cb = new getNameOfPrinterCallBack(getNameOfPrinter);
return (string)Invoke(cb, new object[] { name });
}
else {
search = this._listOfCategories.FindItemWithText(name, false, 0);
return this._listOfCategories.Items[search.Index].SubItems[1].Text;
}
}
}
And I call the function getNameOfPrinter
in a timer (5 in 5 seconds). The first time it works properly, the second time and further it starts giving me the error:
An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll
The line that prints the error is return (string)Invoke(cb, new object[] { name });
This happens because I'm trying to implement a way of avoid the error of Cross Threading. What am I doing wrong with my code?