tags:

views:

89

answers:

3

Hi, 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 ?

+1  A: 

To be honest, I'd just use

BeginInvoke((MethodInvoker)delegate {
    UpdateSales(numbersale);
});

That way:

  • no need to declare a delegate type
  • static type checking
  • MethodInvoker has special detection/handling, so is slightly faster ( not much)

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.

Marc Gravell
+1  A: 

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)
{

}
Fara
A: 
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.

naacal