Reputation: 309
I am making a C# program which is runnning 2 threads. The main UI thread, and a seperate network thread i make myself.
I have figured out, that if i need to change something in the UI from the network thread, i will need to call a deligate method, which works just fine:
// Declared as a global variable
public delegate void ListBoxFirst();
//Then call this from the network thread
listBox1.BeginInvoke(new ListBoxFirst(InitListBox));
//Which points to this
public void InitListBox() {
listBox1.SelectedIndex = 0;
}
Now i need to be able to read a UI value (a listbox.selectedindex) from the network thread, but it shows the error "cannot implicitly convert type 'system.iasyncresult' to 'int'" if i try it the same way (of course with "int" instead of "void", and a "int a = " before the listbox1.begininvoke). I have googled a lot but im pretty new to C# so i get really lost.
Any help would be much appriciated
Upvotes: 1
Views: 6596
Reputation: 1
This works also, where tn
is the treenode you want added to cross thread and tnret
is the treenode that is returned.
_treeView.Invoke(new Action(() => tnret = tn.Nodes.Add( name, name )));
Upvotes: 0
Reputation: 309
I figured it out:
public int ReadListBoxIndex()
{
int count = 0;
listBox1.Invoke(new MethodInvoker(delegate
{
count = listBox1.SelectedIndex;
}));
return count;
}
Called with a regular
int count = ReadListBoxIndex();
Upvotes: 2
Reputation: 16555
You need to call EndInvoke()
to get the result.
Some code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.Items.AddRange(new[] { "AS","Ram"});
}
protected override void OnLoad(EventArgs e)
{
listBox1.BeginInvoke(new Action(GetResult));
}
private void GetResult()
{
if (InvokeRequired)
{
Invoke(new Action(GetResult));
}
listBox1.SelectedIndex = 0;
}
}
Upvotes: 0