Nuru Salihu
Nuru Salihu

Reputation: 4928

Please i want to know what the differences between these two delegates are?

I am trying to use delegate to return combox selected index in c# form. However, when i use the method below it works.

 delegate void dttypeDelegate();

object searchType = Invoke(new dttypeDelegate(() =>
           {
              return dbtype.SelectedIndex;

           }));

The above method return the combobox selected index to an object searchtype which i m able to retrieve in a form of string. However, the method.

delegate int dttypeDelegate();
 private int searchType()
        {
            int i = 0; 
            if (dbtype.InvokeRequired)
            {
                dttypeDelegate dt = new dttypeDelegate(searchType);
                this.Invoke(dt);
            }
            else
            {
                i = dbtype.SelectedIndex; 
            }


          i = dbtype.SelectedIndex; 

           return i;

        }

Throws an exception on that dbtype.SelectedIndex; is accessed from the thread other than the method it was made.PLs i wan to know why the exception ? what are the different between the two?

Upvotes: 0

Views: 82

Answers (2)

Nuru Salihu
Nuru Salihu

Reputation: 4928

Thank you all for the answers. I saw a similar delegate here that solve my problem . i just need to pass this.Invoke(dt); to i first or just return it as a return value.

  private int searchType()
        {
            int i = 0;
            if (dbtype.InvokeRequired)
            {

                dttypeDelegate dt = new dttypeDelegate(searchType);
                i = (int)this.Invoke(dt);
                return i;
            }
            else
            {
               return i = dbtype.SelectedIndex; 
            }



        }

I saw this in the here

Upvotes: 0

Sam Axe
Sam Axe

Reputation: 33738

private int searchType()
        {
            int i = 0; 
            if (dbtype.InvokeRequired)
            {
                dttypeDelegate dt = new dttypeDelegate(searchType);
                this.Invoke(dt);   // <--- marshal to UI thread
            }
            else
            {
                i = dbtype.SelectedIndex; 
            }


          i = dbtype.SelectedIndex; // <--- now we're back on the non-UI thread.

           return i;
        }

You need to exit the method after the Invoke.

Upvotes: 1

Related Questions