How to use the Invoke method in an extension / method file?

Well, I am writing a file of extensions / methods useful for strings, labels, links, classes, etc.

but i have a problem. I have a showMessage() method that changes the label text, works fine. But I decided to do this while working with thread execution, then I do this:

 namespace LabelExtensions { public static class LabelExtensionsClass { private delegate void UpdateState(); public static void ShowMessage(this Label label, string text) { if (label.InvokeRequired) { label.Invoke((UpdateState)delegate { label.Text = text; }); } else { label.Text = text; } } } } 

Sorry , that was a typo. I typed this code in the forum. the error continues.

according to the documentation , to use the Invoke method, you must import:

Namespace: System.Windows.Forms

Build: System.Windows.Forms (in System.Windows.Forms.dll)

then I did:

 using System.Windows.Forms; 

but this returns the same error:

 The name 'Invoke' does not exist in the current context 

How can I fix it?

Thanks in advance.

+7
source share
5 answers

Why not just do it:

 label.BeginInvoke( (Action) (() => label.Text = text)); 

No need to create your own delegate. Just use the built-in Action delegate. You should probably create your extension method for the Control base class instead of the Label class. It will be more reusable.

+8
source

Edit

 Invoke((UpdateState)delegate 

to

 label.Invoke((UpdateState)delegate 
+3
source

You forgot to specify the label in your code (when you call the Invoke method):

 public static void ShowMessage(this Label label, string text) { if (label.InvokeRequired) { lablel.Invoke((UpdateState)delegate { label.Text = text; }); } else { label.Text = text; } } 

also consider using BeginInvoke so as not to block the calling thread (if applicable)

+1
source

Invoke is a Control instance method.
To call it you need Control , for example label .

+1
source

You do not need to declare a new delegate type or create a new lambda or anonymous delegate. You already have a method that acts on the UI thread - the one you write. Just make it call itself in a user interface thread like this.

 public static void ShowMessage(this Label label, string text) { if(label.InvokeRequired) { label.Invoke(new Action<Label, string>(ShowMessage), label, text); return; } label.Text = text; } 

The advantage of this approach is that you can almost copy and paste a block of redirection code from this method into any other method that you want to change in the same way.

+1
source

All Articles