使用匿名方法有任何开销吗? [英] Is there any overhead in the use of anonymous methods?

查看:90
本文介绍了使用匿名方法有任何开销吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在创建后台工作程序时是否通过使用匿名方法而产生任何开销。

I would like to know if there is any overhead incurred through the use of anonymous methods when creating a Background worker.

例如:

public void SomeMethod()
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (sender, e) =>
    {
        //large amount of code
    }

    worker.RunWorkerAsync();
}

上面的示例会比定义<$ c $好还是坏? c> //大量代码用单独的方法?

Would the example above be any better or worse than defining the //large amount of code in a separate method?

内联定义后台工作程序方法是否会产生开销,尤其是如果经常调用 SomeMethod()

Is there any overhead incurred in defining the background worker method in-line, particularly if SomeMethod() is called often?

推荐答案

在从它们创建委托时,命名方法和匿名方法的处理方式差别很小。

There is a small difference in how named methods and anonumous methods are handled when you create a delegate from them.

缓存了匿名方法的委托,因此检查是否有少量开销委托已经存在于缓存中。另一方面,如果您多次运行该方法,它将重复使用缓存的委托,而不是创建一个新的委托。

Delegates for anonymous methods are cached, so there is a small overhead for checking if the delegate already exists in the cache. On the other hand, if you run the method more than once, it will reuse the cached delegate instead of creating a new one.

命名方法的委托不会被缓存,

Delegates for named methods are not cached, so it will be created each time.

除此之外,没有区别。匿名方法将在编译时创建,并且像常规方法一样存在于代码中,仅使用只有编译器才知道的名称。

Other than that there is no difference. The anonumous method will be created at compile time and exists in the code just like a regular method, only with a name that only the compiler knows about.

这篇关于使用匿名方法有任何开销吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆