I was testing thread-safety for better grasp and this is what I did :
I have a Type called ThreadSample which has two methods and this where locking is happening :
internal class ThreadTime
{
public void doSomething(string message)
{
lock (this)
{
DialogResult t = MessageBox.Show(message);
Thread.Sleep(2000);
}
}
public void anotherLife(string message)
{
MessageBox.Show("This is coming from anotherLife method and and current threadNumber is " + message);
}
}
Basically the idea is when doSomething() is called, it should lock the entire objects and other threads can even invoke anotherLife method since they are waiting for other threads to release the lock.
This is the logic to simulate lock-release :
public partial class Form1 : Form
{
private ThreadTime time;
private Thread thread;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(workerThread));
time = new ThreadTime();
}
private void button1_Click(object sender, EventArgs e)
{
thread.Start();
//Thread.Sleep(1000);
time.anotherLife("Current thread is = " + "UI Thread");
}
private void workerThread()
{
//time.doSomething("Current thread is = " + Thread.CurrentThread.ManagedThreadId);
time.doSomething("Worker Thread");
}
}
As you can see in the code right below :
When Form is being initialized, a new Thread and ThreadSample are created. Then when user clicks on the button1, thread is started and the UIThread is reaching and invoking anotherLife which is not thread-safe at first.
Anyways, the output is :
- There are two MessageBox shown at the same time.
What I was expecting is when the new Thread invokes doSomething(), it gets the lock of the object and UIThread waits for the lock to be released to be able to invoke anotherLife method.
Can some one explain why?
Thanks.
UIThread won’t wait for a lock to be released before allowing
anotherLifeto proceed becauseanotherLifeis not performing a lock. Both threads have to run into alockstatement (locking on the same object) in order to get the behavior you’re looking for. Try modifying it to something like: