Vincent Dagpin
Vincent Dagpin

Reputation: 3611

Update control from another thread in C# 2.0

I'm using this code with .NET 3.0

Action xx = () => button1.Text = "hello world";
this.Invoke(xx);

but when i tried it in .NET 2.0, I think Action has type parameter like this:

Action<T>

How to implement the first code in .NET 2.0?

Upvotes: 5

Views: 513

Answers (2)

Josh Smeaton
Josh Smeaton

Reputation: 48730

Action<T> is the signature, which just means that the method represented by the action must take a single parameter. What the type of the parameter is, depends on the signature of the Invoke call.

Some code examples of how to represent the various signatures of Action:

var noArgs = () => button1.Text = "hello world"; // Action
var oneArg = (arg) => button1.Text = "hello world"; // Action<T>
var twoArgs = (arg1, arg2) => button1.Text = "hello world"; // Action<T,T>

If you don't need to use the parameters to the method, that's fine. But you still need to declare them in the lambda expression.

Now, this doesn't answer how to do it from .NET 2.0, but I assumed (perhaps incorrectly, correct me if I'm wrong) that you weren't aware how lambdas correspond to Action types.

Upvotes: 1

Alex Aza
Alex Aza

Reputation: 78507

Try this:

this.Invoke((MethodInvoker) delegate
{
    button1.Text = "hello world";
});

Although Action was introduced in .NET 2.0, you cannot use lambda expression () => ... syntax in .NET 2.0.

BTW, you can still use Action in .NET 2.0, as long as you don't use lambda sytax:

Action action = delegate { button1.Text = "hello world"; };
Invoke(action);

Upvotes: 6

Related Questions