Imagine that you have two buttons in the form of a win. What do you think should be the behavior when the user clicks the "1" button using the code below?
Should it display all 5 message boxes at a time or one after another - is the MessageBox.Show expression inside the lock statement?
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private static readonly object lockobject = new object(); private void button1_Click(object sender, EventArgs e) { var action = new Action(function); for(int i = 0; i< 5; i++) { action.BeginInvoke(null, null); } } private void function() { if (button2.InvokeRequired) { var func = new Action(function); button2.Invoke(func); } else { lock (lockobject) { MessageBox.Show("Testing"); } } } }
Now, if we replace MessageBox.Show with any other status, it will execute the operator only one at a time, the rest of the threads will wait one at a time.
source share