[英]C# method lock doesn't work
I have an exe file that needs to run multiple times. 我有一个需要多次运行的exe文件。
In the C# code I have a method that reads some value from the database and changes it. 在C#代码中,我有一个方法可以从数据库中读取一些值并进行更改。 I want to prevent more than one exe command getting this method. 我想防止多个exe命令获得此方法。 I tried to use lock mechanism but it doesn't work 我尝试使用锁定机制,但没有用
private static readonly object locker = new object();
private void myFunc()
{
lock (locker)
{
//my code
}
}
lock
is only valid at thread level (inside one process). lock
仅在线程级别 (在一个进程内)有效。
I have an exe file that need to run multiply times. 我有一个需要多次运行的exe文件。
If you use multiple process to achieve your task, you should use a use Mutex instead. 如果使用多个过程来完成任务,则应改用use Mutex 。
Here is way to do it: 这是这样做的方法:
private static Mutex mut = new Mutex(false, "MyFuncLock") ;
private void myFunc()
{
mut.WaitOne();
//your code
mut.ReleaseMutex();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.