Why is Lock used ?, Lock usage,
When multiple processes share data, lock the code of a program (when the shared data is rewritten ).
Let's take a look at this Code:
namespace ThreadTest{ class Program { static bool done; static void Main(string[] args) { new Thread(Go).Start(); Go(); Console.ReadKey(); } static void Go() { if (!done) {
done = true;
Console.WriteLine("Done");
}
}
}
}
The field "Done" is shared by two processes, so a "Done" is output, but if we reverse the two programs:
static void Go() { if (!done) { Console.WriteLine("Done"); done = true; } }
Before a process can set "done" to true, another process may have output, which greatly increases the possibility of outputting two dones.
Therefore, we need to lock. When assigning values to shared variables, we can lock the program so that another process can only wait until the lock is released.
static bool done; static readonly object locker = new object(); static void Main(string[] args) { new Thread(Go).Start(); Go(); Console.ReadKey(); } static void Go() { lock(locker) { if (!done) { Console.WriteLine("Done"); done = true; } } }