gpt4 book ai didi

c# - C# 中的 lock 关键字

转载 作者:IT王子 更新时间:2023-10-29 03:54:40 27 4
gpt4 key购买 nike

从MSDN上了解到lock关键字的主要作用

lock Statement (C# Reference)

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

什么时候应该使用锁?

例如,它对多线程应用程序很有意义,因为它可以保护数据。但是当应用程序不剥离任何其他线程时是否有必要?

使用锁是否存在性能问题?

我刚刚继承了一个到处都在使用锁的应用程序,它是单线程的,我想知道我是否应该保留它们,它们是否有必要?

请注意,这更像是一个常识性问题,应用程序速度还不错,我想知道这是否是将来可以遵循的良好设计模式,或者除非绝对需要,否则应该避免这种情况。

最佳答案

When should the lock be used?

应该使用锁来保护多线程代码中的共享资源。不为别的。

But is it necessary when the application does not spin off any other threads?

绝对不是。这只是浪费时间。但是请确保您没有隐式使用系统线程。例如,如果您使用异步 I/O,您可能会收到来自随机线程的回调,而不是您的原始线程。

Is there performance issues with using lock?

是的。它们在单线程应用程序中不是很大,但为什么要进行不需要的调用?

...if that is a good design pattern to follow in the future[?]

随意锁定所有内容是一种糟糕的设计模式。如果您的代码因随机锁定而变得杂乱无章,然后您决定使用后台线程来完成某些工作,那么您很可能会遇到死锁。在多个线程之间共享资源需要仔细设计,越能隔离棘手的部分越好。

关于c# - C# 中的 lock 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com