C# anonymus 代表效率/安全
我有哪个委托的进度:
// in ProgressForm thread
public delegate void executeMethod(object parameters);
private executeMethod method;
public object parameters;
// ...
private void ProgressForm_Shown(object sender, EventArgs e)
{
method.Invoke(parameters);
}
应用哪种方式更好(更高效或更安全) - 匿名委托像这样调用:
// in other thread
ProgressForm progress = new ProgressForm();
progress.ExecuteMethod = delegate
{
// to do
}
或使用像这样的单独方法:
// in other thread
private void myMethod(object par)
{
// to do
}
progress.ExecuteMethod = this.myMethod;
I have progress form which delegate:
// in ProgressForm thread
public delegate void executeMethod(object parameters);
private executeMethod method;
public object parameters;
// ...
private void ProgressForm_Shown(object sender, EventArgs e)
{
method.Invoke(parameters);
}
Which way is better (mor efficient or safe) to apply - anonymus delegates call like this:
// in other thread
ProgressForm progress = new ProgressForm();
progress.ExecuteMethod = delegate
{
// to do
}
or using separate method like this:
// in other thread
private void myMethod(object par)
{
// to do
}
progress.ExecuteMethod = this.myMethod;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
归根结底,它们惊人地相似。简而言之,编译器在内部为匿名情况创建隐藏方法。尽管在某些情况下它可能会选择创建静态方法(如果它不使用
this
或任何捕获的变量),但没有具体的性能差异 - 这可能会有所帮助 em>(但还不足以令人兴奋)我会在以下情况下使用匿名方法:
主要要注意的是臭名昭著的 foreach (通常)捕获的变量陷阱,但在某些情况下,也有可能将引用渗入匿名方法,意外地延长了大对象的生命周期。
对于较长的工作,我会使用
myMethod
方法。Ultimately they are surprisingly similar; simply, the compiler creates the hidden method internally for the anonymous case. There is no specific performance difference, although there are cases when it might choose to create a static method (if it doesn't use
this
or any captured variables) - that may help marginally (but not enough to get excited about)I would use an anonymous method when:
myMethod
The main thing to watch is the notorious
foreach
(typically) captured variable gotcha, but in some cases it is also possible to bleed a reference into the anonymous method, extending the life-time of a big object unexpectedly.For longer work, I would use the
myMethod
apprach.性能是相同的。与其他方法一样,匿名委托由编译器转换为常规方法。如果您 ILDSM 代码,您将看到为匿名方法生成了真实的(但隐藏的)名称。
The performance is identical. An anonymous delegate is converted by the compiler into a regular method like any other. If you ILDSM the code you'll see that a real (but hidden) name is generated for the anonymous method.