C# lock(mylocker) not work

折月煮酒 提交于 2019-12-04 03:39:57

I suspect your problem here is that your lock is an instance member rather than a static (type level) member.

Assuming that each thread has its own instance of the containing class, then it'll also have its own instance of your locker - which is not what you want.

Try this declaration instead:

private static readonly object locker = new object();

The inclusion of the static keyword now makes this object instance exist at the type level, i.e. shared across all instances of your class.

You will have to make the object static.

  private static readonly object locker = new object();

Currently every instance of the class (and therefore every thread) has its own instance of the locker.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!