Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 851
Vincent Dagpin Avatar asked Jun 19 '11 03:06

Vincent Dagpin


People also ask

How would you update an UI element when two threads are accessing it simultaneously?

The solution is to call control. BeginInvoke, passing in a MethodInvoker delegate. The code in the delegate will be executed on the UI thread, hence allowing you to update the UI. Note: BeginInvoke() is asynchronous.

Can we update UI from thread?

However, note that you cannot update the UI from any thread other than the UI thread or the "main" thread. To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: Activity.

What is a UI thread?

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.


2 Answers

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);
like image 158
Alex Aza Avatar answered Oct 06 '22 01:10

Alex Aza


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.

like image 27
Josh Smeaton Avatar answered Oct 06 '22 03:10

Josh Smeaton