lock keyword in C#

前端 未结 10 874
南旧
南旧 2020-11-30 03:54

I understand the main function of the lock key word from MSDN

lock Statement (C# Reference)

The lock keyword marks a statement block as

相关标签:
10条回答
  • 2020-11-30 04:22

    Generally speaking if your application is single threaded, you're not going to get much use out of the lock statement. Not knowing your application exactly, I don't know if they're useful or not - but I suspect not. Further, if you're application is using lock everywhere I don't know that I would feel all that confident about it working in a multi-threaded environment anyways - did the original developer actually know how to develop multi-threaded code, or did they just add lock statements everywhere in the vague hope that that would do the trick?

    0 讨论(0)
  • 2020-11-30 04:22

    Lock(token) is only used to mark one or more blocks of code that should not run simultaneously in multiple threads. If your application is single-threaded, it's protecting against a condition that can't exist.

    And locking does invoke a performance hit, adding instructions to check for simultaneous access before code is executed. It should only be used where necessary.

    0 讨论(0)
  • 2020-11-30 04:27

    When should the lock be used?

    A lock should be used to protect shared resources in multithreaded code. Not for anything else.

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

    Absolutely not. It's just a time waster. However do be sure that you're not implicitly using system threads. For example if you use asynchronous I/O you may receive callbacks from a random thread, not your original thread.

    Is there performance issues with using lock?

    Yes. They're not very big in a single-threaded application, but why make calls you don't need?

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

    Locking everything willy-nilly is a terrible design pattern. If your code is cluttered with random locking and then you do decide to use a background thread for some work, you're likely to run into deadlocks. Sharing a resource between multiple threads requires careful design, and the more you can isolate the tricky part, the better.

    0 讨论(0)
  • 2020-11-30 04:30

    Yes, there will be some performance penalty when using lock but it is generally neglible enough to not matter.

    Using locks (or any other mutual-exclusion statement or construct) is generally only needed in multi-threaded scenarios where multiple threads (either of your own making or from your caller) have the opportunity to interact with the object and change the underlying state or data maintained. For example, if you have a collection that can be accessed by multiple threads you don't want one thread changing the contents of that collection by removing an item while another thread is trying to read it.

    0 讨论(0)
提交回复
热议问题