线程最佳实践 [英] Threading Best Practices

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

问题描述

我从事的许多项目的线程实现都很差,而且我是个笨拙的人,必须跟踪这些问题.有没有公​​认的最佳方式来处理线程.我的代码始终在等待永远不会触发的事件.

Many projects I work on have poor threading implementations and I am the sucker who has to track these down. Is there an accepted best way to handle threading. My code is always waiting for an event that never fires.

我有点像设计模式之类的东西.

I'm kinda thinking like a design pattern or something.

推荐答案

(假设.NET;类似的情况也适用于其他平台.)

(Assuming .NET; similar things would apply for other platforms.)

好吧,有很多值得考虑.我建议:

Well, there are lots of things to consider. I'd advise:

  • 不可移植性对于多线程非常有用.函数式编程可以同时很好地运行,部分原因在于对不变性的重视.
  • 在访问可变的共享数据(包括读写)时使用锁.
  • 除非真的需要,否则不要尝试无锁.锁很贵,但瓶颈很少.
  • Monitor.Wait应该几乎总是 成为条件循环的一部分,等待条件变为真,然后再次等待.
  • 尝试避免持有锁的时间超出您的需要.
  • 如果您需要一次获取两个锁,请彻底记录订单并确保始终使用相同的订单.
  • 记录类型的线程安全性.大多数类型不需要都必须是线程安全的,它们只需要不需要线程有害(即您可以从多个线程中使用它们,但这是的责任"如果要共享,请拿出锁)
  • 请勿从非UI线程访问UI(除非已记录的线程安全方式).在Windows窗体中,使用Control.Invoke/BeginInvoke
  • Immutability is great for multi-threading. Functional programming works well concurrently partly due to the emphasis on immutability.
  • Use locks when you access mutable shared data, both for reads and writes.
  • Don't try to go lock-free unless you really have to. Locks are expensive, but rarely the bottleneck.
  • Monitor.Wait should almost always be part of a condition loop, waiting for a condition to become true and waiting again if it's not.
  • Try to avoid holding locks for longer than you need to.
  • If you ever need to acquire two locks at once, document the ordering thoroughly and make sure you always use the same order.
  • Document the thread-safety of your types. Most types don't need to be thread-safe, they just need to not be thread hostile (i.e. "you can use them from multiple threads, but it's your responsibility to take out locks if you want to share them)
  • Don't access the UI (except in documented thread-safe ways) from a non-UI thread. In Windows Forms, use Control.Invoke/BeginInvoke

那太过分了-如果这对您有用的话,我可能会想更多,但是如果没有用,我会停在那儿.

That's off the top of my head - I probably think of more if this is useful to you, but I'll stop there in case it's not.

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

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