Duplicate question. Answer here ...
Lock aqcuired and further attempts to lock do not block: are C# locks re-entrant?
Basically (copied from link above):
Locks in .NET are reentrant. Only acquisitions from other threads are blocked. When the same thread locks the same object multiple times, it simply increments a counter, and decrements it when released. When the counter hits zero, the lock is actually released for access from other threads.
c# .net 4.8 winforms. One button, one multiline textbox.
Simple app - click on button, it waits 2 seconds (doevents for 2 seconds), it writes out.
I clicked the button 6 times, about a second apart. I am aware the doevents allows more click events to be picked up. I can see that the lock is not waiting before processing is finished for previous click., and that the events are finishing in reverse order.
Q1 - Why is the lock not locking?
Q2 - why are the click events completed in reverse order?
Q3 -What's actually happening here?
using System.Windows.Forms;
namespace WindowsFormsApplication_testlock
{
public partial class Form1 : Form
{
object _objLock;
int _intIteration;
System.Collections.Generic.Dictionary<int, DateTime> _lstIterationsTimes;
public Form1()
{
InitializeComponent();
_objLock = new object();
_intIteration = 0;
_lstIterationsTimes = new Dictionary<int, DateTime>();
}
private void button1_Click(object sender, EventArgs e)
{
_intIteration++;
_lstIterationsTimes.Add(_intIteration, DateTime.Now);
Process(_intIteration);
}
private void Process(int intIteration)
{
textBox1.Text += "About to lock - " + intIteration.ToString() + Environment.NewLine;
lock (_objLock)
{
textBox1.Text += "Succeeded to lock - " + intIteration.ToString() + Environment.NewLine;
while ( (DateTime.Now - _lstIterationsTimes[intIteration]).TotalSeconds < 2)
{
Application.DoEvents();
}
textBox1.Text += "About to unlock - " + intIteration.ToString() + Environment.NewLine ;
}
}
}
}
Output:
About to lock - 1
Succeeded to lock - 1
About to lock - 2
Succeeded to lock - 2
About to lock - 3
Succeeded to lock - 3
About to lock - 4
Succeeded to lock - 4
About to lock - 5
Succeeded to lock - 5
About to lock - 6
Succeeded to lock - 6
About to unlock - 6
About to unlock - 5
About to unlock - 4
About to unlock - 3
About to unlock - 2
About to unlock - 1