Reputation: 35522
I use the code below to access the properties on my form,but today I'd like to write stuff to a ListView,which requires more parameters.
public string TextValue
{
set
{
if (this.Memo.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
this.Memo.Text += value + "\n";
});
}
else
{
this.Memo.Text += value + "\n";
}
}
}
How to add more than one parameter and how to use them(value,value)?
Upvotes: 14
Views: 28027
Reputation: 480
Generically, You can do as follow
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Lambda1
{
public partial class Form1 : Form
{
System.Timers.Timer t = new System.Timers.Timer(1000);
Int32 c = 0;
Int32 d = 0;
Func<Int32, Int32, Int32> y;
public Form1()
{
InitializeComponent();
t.Elapsed += t_Elapsed;
t.Enabled = true;
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
c = (Int32)(label1.Invoke(y = (x1, x2) =>
{ label1.Text = (x1 + x2).ToString();
x1++;
return x1; },
c,d));
d++;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Enabled = false;
}
}
}
What this code do is:
A timer is created. The Elapsed Event Handler
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
will be called every 1000ms
The label1.Text will be updated inside this event handler. Without the Invoke, there will be a thread issued
To update the label1.Text with a new value, the code was used
c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +
x2).ToString(); x1++; return x1; }, c,d));
Please see that c and d are being passed as argument to x1 and x2 in the the Invoke function and x1 is returned in the Invoke call.
The variable d was inserted in this code just to show how to pass more than one variable when Invoke is called.
Upvotes: 0
Reputation: 1062770
(edit - I think I misunderstood the original question)
Simply make it a method instead of a property:
public void DoSomething(string foo, int bar)
{
if (this.InvokeRequired) {
this.Invoke((MethodInvoker)delegate {
DoSomething(foo,bar);
});
return;
}
// do something with foo and bar
this.Text = foo;
Console.WriteLine(bar);
}
Upvotes: 33