C# 实时尝试捕捉 [英] C# Real Time Try Catch

查看:62
本文介绍了C# 实时尝试捕捉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望得到真正使用 C# 进行实时编程或真正了解语言内部结构的人的回复.

I'd like a response from someone who actually does real-time programming in C# or who really understands the language internals.

我知道异常不应用于处理正常处理,而应仅用于检测错误情况.关于这个话题有很多讨论.

I know that exceptions should not be used to handle normal processing, but only to detect error conditions. There is plenty of discussion on that topic.

我想知道是否会因为简单地放置一个 try/catch 块而导致运行时间变慢(除非程序无论如何都必须结束,否则它永远不会捕获异常).try/catch 块位于必须重复调用的函数内.我怀疑只有最低限度的成本.

I'd like to know if there is any run time slow-down from simply having a try/catch block in place (which never catches an exception unless the program will have to end anyway). The try/catch block is inside a function which must be called repeatedly. I suspect there is only minimal cost.

是否可以根据 CPU 周期或其他任务(与浮点乘法的成本相同)或其他方式来量化成本?

Can the cost be quantified in terms of CPU cycles, or other tasks (same cost as a floating point multiplication), or another way?

我们在 windows XP 下使用 Microsoft C#.Net 3.5.

We use Microsoft C#.Net 3.5 under windows XP.

推荐答案

.NET 异常的开销非常非常低,除非它们被抛出.使用 try/catch 块将对性能产生非常小的影响.我发现即使在非常快速、紧凑的循环中,异常处理也几乎没有影响.

.NET exceptions have a very, very low overhead cost unless they are thrown. Having a try/catch block in place will have a very minimal performance impact. I have found nearly no impact, even in very fast, tight loops, to having exception handling in place.

然而,.NET 中的异常在抛出时非常昂贵.如果你抛出它们,它们往往会对性能产生很大的影响,而不是许多其他语言.这是由于创建异常时收集的完整堆栈信息等.

However, exceptions in .NET are VERY expensive when they're thrown. They tend to be much high-impact on performance if you throw them than many other languages. This is due to the full stack information gleaned when the exception is created, etc.

这与其他一些语言(例如 python)的行为相反,其中异常处理的成本更高,但抛出实际上相当高效.

This is the opposite behavior to some other languages, such as python, where exception handling has a higher cost, but throwing is actually fairly performant.

但是,如果您担心,我建议您描述您的日常工作,并自己测试一下.这是我在进行了相当多的性能分析之后的经验.在您自己的代码库中测量是不可替代的.

However, if you are concerned, I would suggest you profile your routine, and test it yourself. This has been my experience after quite a bit of performance profiling. There is no substitution for measuring in your own codebase.

这篇关于C# 实时尝试捕捉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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