C#中线程同步有哪些方法
除了使用 lock(object) 关键字之外,在某些情况下是否有任何根本不同或棘手或其他有用的方法来进行同步?
Apart from using lock(object) keyword, are there any fundamentally different or tricky or other useful in some situations ways to do syncronization ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Windows.Threading
命名空间。监视器
和Mutex
是两个重要的类命名空间内的同步(还有其他)。Lock
是简单的Monitor
操作的语法糖。Interlocked
提供了一些线程安全操作(递增
、递减
等)。我建议浏览 MSDN 文档以了解命名空间和其中的不同类。
There are many classes in the
Windows.Threading
namespace.Monitor
andMutex
being two important classes for synchronization within the namespace (there are others).Lock
is syntactic sugar for simpleMonitor
operations.Interlocked
provides some thread safe operations (Increment
,Decrement
and more).I suggest going through the MSDN documentation for the namespace and different classed in it.
如果您需要向一个线程通知另一线程上的事件,则
ManualResetEvent
和AutoResetEvent
允许您这样做。如果您发现您的代码可以处理同时读取,但需要同步写入,并且您的读取比写入更频繁,那么
ReaderWriterLock
(或现在ReaderWriterLockSlim
)将是有很大帮助。Mutex
和Semaphore
提供与lock()
类似的功能,但可用于跨进程同步。还有其他一些,但这些是我通常使用的三个主要其他。
If you need to notify one thread of an event on a different thread, then
ManualResetEvent
andAutoResetEvent
allow you to do so.If you find that your code can handle simultaneous reads but need to synchronize writes, and your reading occurs much more frequently than your writes, then
ReaderWriterLock
(or nowReaderWriterLockSlim
) will be of much help.Mutex
andSemaphore
provide similar functionality tolock()
, but can be used to synchronize across processes.There are some others, but those are the three main others I typically use.
这个问题很广泛。
有一些关于不同同步技术以及在哪种情况下使用哪些技术的书籍。
有很多不同的方法可以进行同步。
同步基元概述< /a>
.NET 4 中添加了相当多的新同步原语。 http: //msdn.microsoft.com/en-us/library/dd460718.aspx
The question is very broad.
There are books about different synchronization technics and which to use in which scenario.
There are a lot of different ways to do synchronization.
Overview of Synchronization Primitives
Quite a few of new synchronization primitives where added in .NET 4. http://msdn.microsoft.com/en-us/library/dd460718.aspx