Adriaan W

What is the best why to do the invoke when working with threads I have this procedure, this works. Here I use the Control (this.txtAction) Invoke method.

private void SetTxtAction(string t)
{
    if (this.txtAction.InvokeRequired)
    {
        MyDelegates.setText d = new MyDelegates.setText(this.SetTxtAction);
        this.txtAction.Invoke(d, new object[] { t });

    }
    else
    {
        this.txtAction.Text = t;
    }
}


My question is if there are any performance or other differences if I would use...

this.Invoke(d, new object[] { t });



*** is there a way to format the text as code when posting code in this forum

Thx
Adriaan


Re: Visual C# General this.Invoke OR Control.Invoke ??

Mark Dawson

Hi,

I personally use the first way, this.txtAction.Invoke since you may have created the text label on a different thread to the control on which it is added, not very likely but I like the first method more.

To format the code, first copy it into notepad or MS word, then copy from their into the posting window and it will keep its formatting.

Mark.






Re: Visual C# General this.Invoke OR Control.Invoke ??

Adriaan W

thx for your opinion !!


Another question that came up was what to do when an object has no Invoke method. For example a contextmenu object has no Invoke method. In my code I use this.InvokeRequired and this.Invoke. Is this a correct way


The tip to paste code is maybe misunderstand by you It's more with colors that I want. It is like in this forum thread (second post):
http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=1221873&SiteID=1




Re: Visual C# General this.Invoke OR Control.Invoke ??

Andreas Johansson

If you copy and paste into word first and then here you will keep colors and formatting.

There should only be minor difference between invoking a delegate on the form compared to a control on the form. The reference to an control (or form) should just be to determine what the UI thread is and the Invoke() method ensures the code is executed in that thread.

this.Invoke() should be as fast as this.txtAction.Invoke() as I assume they are both known by compile time meaning they will both be known references and accessed equally.






Re: Visual C# General this.Invoke OR Control.Invoke ??

Peter Ritchie

Currently (it was supposed to change in Vista; but I think that go dropped) controls need to be created on the same thread as the the parent. You can probably create a control on a different thread and assign a parent from another thread to it; but it's not supported.

It's more clear to use the Invoke on the control, rather than the form; but not necessary.