Imagine you have two buttons on the win form. What do you think should be the behavior when user presses the "button 1" with the below code?
Should it display all 5 message box in one go, or one by one - MessageBox.Show statement is inside a 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 statment, it would execute the statement only one at a time, the other threads would wait, one at a time.