user3398315
user3398315

Reputation: 331

Threading - make sure the thread finishes in C#

There is this thread with the same name but different purpose Threading - make sure the thread finishes

This is a method that got attached to an event using the +=.

public void MsgBox(Int i, Int j)
{
     MessagBox.Show ("a");
     MessagBox.Show ("b"); //it was not MessageBox.Show ("b") in the original code.
     // It was something that is more time consuming for the computer
} 

I will get MessageBox of value a,a,a,b,b,b

After doing some debugging, I realised before MessageBox.Show("b") can be called, the event invoke another MsgBox instance thus leading to a,a,a,b,b,b

Upvotes: 0

Views: 85

Answers (2)

oleksii
oleksii

Reputation: 35895

I take it you want to have syncronisation between several threads, so that you get an output like

"ab ab ab"

Instead of

"aa ab bb" or "aa ba bb" or "ab aa bb" ...

For this you can add a common lock, so that all the threads attempt to acquire the same lock

// make sure there is only 1 instance of _obj shared between all threads
// one approach to do this would be to use a static object
private static object _obj = new object();

public void MsgBox(Int i, Int j)
{
    lock(_obj) 
    {
        MessagBox.Show ("a");
        Thread.Sleep(1000);   // simulate work
        MessagBox.Show ("b");
    }
}

Upvotes: 1

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

MessagBox.Show ("a"); is a blocking code that will wait for user interaction while others thread are doing the some thing. so use a Console application instead to understand how threads works.

Upvotes: 0

Related Questions