1

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

1
  • 1
    That's running asynchronously. You can't return read any return value, because it's not done yet. Commented Jul 25, 2012 at 22:07

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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;
        }
    }

1 Comment

Well, i think you misunderstood my question. I did figure out how to set the index to 0. What i need, is to READ the value, not set it.
0

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 )));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.