在C#lock关键字 [英] lock keyword in C#

查看:267
本文介绍了在C#lock关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,锁定键字从MSDN的主要功能


  

lock语句(C#参考)


  
  

锁定关键字标志着声明
  方框由临界区
  获得互斥锁
  对于给定的对象,执行一
  语句,然后释放
  锁定。


在应该锁使用?

比如,它是有道理的多线程应用程序,因为它保护的数据。但它是必要的,当应​​用程序没有分拆任何其他线程?

是否有性能问题,使用锁?

我刚刚继承了无处不在使用锁的应用程序,它是单线程的,我想知道我要离开他们,是他们甚至是必要的?

请注意,这更是一个常识问题,应用程序的速度是好的,我想知道,如果这是一个好的设计模式在未来或遵循本应避免,除非绝对必要的。


解决方案

  

在应该锁使用?


有一个锁应该被用来保护共享资源,在多线程code。不为别的。


  

但它是必要的,当应​​用程序没有分拆任何其他线程?


绝对不是。这只是浪费时间。但是千万要确保你不会隐式使用系统线程。例如,如果您使用异步I / O,你可以从一个随机的线程中接收回调,而不是你原来的线程。


  

是否有性能问题,使用锁?


是的。他们不是在单线程应用程序非常大,但为什么拨打电话则不需要?


  

...如果这是一个好的设计模式在未来遵循[?]


锁定一切不管三七二十一是一个可怕的设计模式。如果你的code堆满了随机锁定,然后你决定使用一个后台线程的一些工作,你可能会碰到死锁。共享多个线程之间的资源需要精心的设计,以及更可以隔离棘手的部分,就更好了。

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

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?

For instance it makes sense with multi-threaded applications because it protects the data. But is it necessary when the application does not spin off any other threads?

Is there performance issues with using lock?

I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary?

Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.

解决方案

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.

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

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