In one of Outlook add in, I have a worker thread that does some processing and then updates a boolean flag. Main thread checks this flag and if this is false , it just process a while loop and does nothing.
//worker thread void DoSoneThing() { Outlook.Recipients recps = mail.Recipients. foreach(Outlook.Recipient recp in recps) { //Save each recipients in a colection } isDone=true; } //Main thread while(!isDone) { //read the collection where recipients name have been stored. }``
if the Main thread comes to this piece of code before the worker thread has set the flag to true, main thread keeps on processing the loop and secondry thread is just kind of paused. and since the isDone flag is never set to true, main thread doesn't do any thing.
When I put a lock in the DoSomeThing method and used the same lock in mian thread, this issue is resolved.
myClass { public static object _syncRoot = new Object(); void DoSoneThing() { lock(_syncRoot) { //process isDone=true; } } } myOtherClass { lock(myClass._syncRoot) { //process } }
My understanding was that lock is used to restrict the entry to same piece of code by more than one thread. But don't understand why worker thread doesn't do any thing when shared resource is accessed by main thread.