I was just doing some random testing when blocking multithreaded this morning, and I strangely found that locking a private "string" in two separate instances actually blocks the execution of another thread. Please find the code below for reference.
What confuses me is that the "string" in two objects is really two separate objects, so why block the other on one block? (Note: if you replace the string with another object of a reference type, such as List, it will not block the execution of another thread, as we expected ...)
class Program { static void Main(string[] args) { Thread th = new Thread(DoWork); th.Start(); Thread th2 = new Thread(DoWork); th2.Start(); } static void DoWork() { Test importer = new Test(); importer.SyncTest(); } } public class Test { public void SyncTest() { string find = "test"; lock(find) { Console.WriteLine("thread starting..."); Thread.Sleep(4000); } } }
source share