多线程 [英] Multi Threading

查看:176
本文介绍了多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学多线程的那一刻,在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?

感谢您的答复。

推荐答案

在除了 MSDN最佳实践,我会添加:


  1. 请不要让你自己的线程。喜欢使用线程池(或新的Task并行库任务)。管理自己的线程很少,如果有的话,正确的设计决策。

  2. 要格外小心与用户界面相关的问题。 Control.Invoke (Windows窗体)和的 Dispatcher.Invoke (WPF),或使用的的SynchronizationContext .Current早报/发送

  3. 倾向于使用的 BackgroundWorker的类在适当的时候。

  4. 尝试通过锁,以保持同步到最低限度

  5. 确保到需要同步

  6. 青睐,在的互锁类时可能超过锁定
  1. 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.
  2. Take extra care with UI related issues. Control.Invoke (Windows Forms) and Dispatcher.Invoke (WPF), or use SynchronizationContext.Current with Post/Send
  3. Favor using the BackgroundWorker class when appropriate.
  4. Try to keep synchronization via locks to a minimum
  5. Make sure to synchronize everything that requires synchronization
  6. 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:


  1. 当心的错误共享。使用数组时,因为每个阵列写入任何数组中的元素包括.NET中的边界检查,这效应导致附近元素0(只是之前的元素0在内存中)阵列上的访问,这是特别有问题的。这可能会导致PERF。下坡大幅走。在循环的情况下工作时

  2. 谨防关闭的问题,尤其是。如果你在一个变量在错误的范围内作出委托时关闭讨厌的错误可能发生。

  1. 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.
  2. 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.

这篇关于多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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