Reputation: 53
This is my first time using delegate in c# application. can some one check if i use this correctly.
int totalsales = 0;
adddata(){
........
BeginInvoke(new UpdateSalesDelegate(UpdateSales), numbersale);
}
private delegate void UpdateSalesDelegate(int args);
private void UpdateSales(int args){
totalsales = totalsales + args;
Label.Text = "Total Sales: " + totalsales.ToString();
}
or should i use
adddata(){
........
BeginInvoke(new UpdateSalesDelegate(UpdateSales), new int numbersale);
}
.................
which way is correct ?
Upvotes: 2
Views: 138
Reputation: 620
Label.Text = "Total Sales: " + totalsales.ToString();
This code will most likely fail, since BeginInvoke()
invokes the delegate asynchronously on a new thread and updating properties on the Label needs to be done on the UI thread.
Upvotes: 0
Reputation: 7011
You can use an action delegate. This saves you from having to specify your own delegate each time.
void AddData()
{
BeginInvoke(new Action<int>(UpdateSales), numbersale);
}
void UpdateSales(int args)
{
}
Upvotes: 1
Reputation: 1062745
To be honest, I'd just use
BeginInvoke((MethodInvoker)delegate {
UpdateSales(numbersale);
});
That way:
It also isn't clear what the async method will do; adding two numbers is overkill, fir example. You may need to consider thread safety and thread affinity.
Upvotes: 1