Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which C# assembly contains Invoke?

Alternate question: Why is VS10 so keen to complain about Invoke?

In my continuing quest to make my app work become the worlds best C# programmer, I have decided that threads are a Good Thing™.

MSDN has a helpful article on making thread-safe calls to controls, but it (and seemingly every other article on the subject) obliquely references a method called Invoke. Sometimes even BeginInvoke, which I've read is to be preferred.

All this would be great, if I could get visual studio to recognise Invoke. MSDN says that it is contained in the System.Windows.Forms assembly, but I'm already 'using' that. To be sure, I've also tried using System.Threading, but to no avail.

What hoops do I need to jump through to get invoke working?

like image 758
Tom Wright Avatar asked Jun 24 '10 11:06

Tom Wright


2 Answers

Invoke is within Control. I.e. Control.Invoke();

There's no way to call Invoke directly as there's no such method in System.Windows.Forms. The Invoke method is a Control Member.

Here's an example I made earlier:

public delegate void AddListViewItemCallBack(ListView control, ListViewItem item);
public static void AddListViewItem(ListView control, ListViewItem item)
{
    if (control.InvokeRequired)
    {
        AddListViewItemCallBack d = new AddListViewItemCallBack(AddListViewItem);
        control.Invoke(d, new object[] { control, item });
    }
    else
    {
        control.Items.Add(item);
    }
}
like image 67
djdd87 Avatar answered Sep 25 '22 04:09

djdd87


You need to call Invoke on an instance of something which contains it - if you're using Windows Forms, that would be a control:

control.Invoke(someDelegate);

or for code within a form, you can use the implicit this reference:

Invoke(someDelegate);

You shouldn't need to go through any particular hoops. If Visual Studio is complaining, please specify the compiler error and the code it's complaining about. There's nothing special about Invoke here.

like image 32
Jon Skeet Avatar answered Sep 23 '22 04:09

Jon Skeet