Threading Question

  • Thread starter Thread starter MDB
  • Start date Start date
M

MDB

Hello All,

I have a background thread whose job is to check for messages. In order to
set values used in the message thread I set global values. My question is,
is it okay for 2 threads to read a global value at the same time? I also
change the global value using the code below, is this alright also?



object initialvalue, newvalue;

do
{
initialvalue = myApp.Classes.Globals.gobjOutGoingCall;
newvalue = false;
}while (initialvalue != Interlocked.CompareExchange(
ref myApp.Classes.Globals.gobjOutGoingCall, newvalue, initialvalue));
 
You need to use thread synchronization like a mutex, lock or monitor to
ensure atomic operations.

-Chris
 
Hi

You will get unpredictable results if you have many threads
writing/reading the same variables without thread synchronisation.

Take a look at the Interlocked class, it allows threads to perform
atomic operations on variables.

Matt
 
No such thing in the CF.

Use proper multithreading techniques like a lock and you'll be fine.

-Chris
 
Back
Top