开发者

c# delegate: Do i use this correctly?

开发者 https://www.devze.com 2023-01-18 18:22 出处:网络
This is my first time using delegate in c# application. can some one check if i usethis correctly. int totalsales = 0;

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: " + totalsa开发者_JS百科les.ToString();

}

or should i use

    adddata(){ 
    ........ 
    BeginInvoke(new UpdateSalesDelegate(UpdateSales), new int numbersale);

    }
.................

which way is correct ?


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.


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

}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消