多线程[关闭](Multi Threading [closed])

编程入门 行业动态 更新时间:2024-10-21 15:57:25
多线程[关闭](Multi Threading [closed])

我现在正在用C#学习多线程,但正如我喜欢学习最佳实践的所有学习一样。 目前该地区似乎模糊。 我了解基础知识,并且可以创建线程。

创建多线程应用程序时应该注意什么? 我应该了解哪些规则或最佳实践? 或者为了避免滑倒,请记住任何事情?

感谢您的回应。

I'm learning Multi Threading at the moment, in C#, but as with all learning I like to learn best practices. At the moment the area seems fuzzy. I understand the basics, and I can create threads.

What should I look out for when creating multi threaded applications. Are there any set rules or best practices that I should know about? Or anything to remember in order to avoid slip ups down the line?

Thanks for the responses.

最满意答案

除了MSDN最佳实践之外 ,我还要补充:

不要自己创建线程。 倾向于使用ThreadPool (或新的“ 任务并行库任务”)。 管理你自己的线程很少,如果有的话,正确的设计决定。 请特别注意与用户界面相关的问题。 Control.Invoke (Windows窗体)和Dispatcher.Invoke (WPF),或使用SynchronizationContext .Current与Post / Send 在适当的时候使用BackgroundWorker类来支持。 尽量保持锁定同步到最低限度 确保同步需要同步的所有内容 在可能的情况下锁定Interlocked类中的方法

一旦你变得更高级,并试图优化,其他事情要寻找:

注意错误分享 。 当使用数组时,这是特别有问题的,因为每个数组写入数组中的任何元素都会在.NET中包含边界检查,这实际上会导致对元素0附近的数组(在存储器中的元素0之前)进行访问。 这可能导致性能下降。 戏剧性地走下坡路。 谨防关闭问题,特别是在循环情况下工作时。 如果您在制作委托时关闭了错误范围内的变量,则可能会出现恶意错误。

In addition to the MSDN Best Practices, I'll add:

Don't make your own threads. Prefer to use the ThreadPool (or the new Task Parallel Library Tasks). Managing your own thread is rarely, if ever, the correct design decision. Take extra care with UI related issues. Control.Invoke (Windows Forms) and Dispatcher.Invoke (WPF), or use SynchronizationContext.Current with Post/Send Favor using the BackgroundWorker class when appropriate. Try to keep synchronization via locks to a minimum Make sure to synchronize everything that requires synchronization Favor the methods in the Interlocked class when possible over locking

Once you get more advanced, and are trying to optimize, other things to look for:

Watch out for false sharing. This is especially problematic when working with arrays, since every array write to any element in an array includes a bounds check in .NET, which in effect causes an access on the array near element 0 (just prior to element 0 in memory). This can cause perf. to go downhill dramatically. Beware of closure issues, especially when working in looping situations. Nasty bugs can occur if you're closing on a variable in the wrong scope when making a delegate.

更多推荐

本文发布于:2023-07-06 07:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   Multi   closed   Threading

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!