Hello All:
I've got a question about synchronization requiremements in a C# worker
thread procedure that, among other things, sinks events from outside
sources. I realize the worker thread will be interrupted to handle an
incoming event (and the flow of execution subsequently diverted to the
respective event handler). My question is at what point or points could
this interruption occur. Will it only occur when the worker thread is
executing a Sleep() or similar call (e.g. Event.WaitOne()) call. Or is it
more complicated than that ... perhaps an I/O call (file, network, etc)
could trigger thread interruption and diversion.
For example, take a look at the following simple p-code, especially the
question posed in the MessageReceived() event handler below. If
synchronization is needed to prevent the null reference exception, how would
I do it since everything (the worker thread proc and the event handler
method) both execute on the same thread. Keep in mind this is just a quick
sample that illustrates my question, my actual coding issue is more
complicated that just updating a shared string.
Thanks in advance,
Bill
The following is just pseudo-code; it won't compile
class MyClass
{
// member variables
const string Name = "MY_CLASS";
string MemberString = null;
bool KeepGoing = true;
// constructor
MyClass
{
MemberString = "fred";
WorkerThread = new Thread(WorkerThreadProc);
WorkerThread.Start();
}
WorkerThreadProc()
{
// subscribe to some event from a 3rd-party library
AnObj.SomethingHappened += new
ObjectX.SomethingHappenedHandler(MessageReceived);
while (KeepGoing)
{
// ************** Section X *************************
MemberString = null;
// do some stuff (maybe retreive a new value for MemberString
from DB)
// *******************************************
MemberString = "Joe";
Thread.Sleep(5000); // or perhaps an Event.WaitOne() call
}
}
// event handler
void MessageReceived(object sender, SomethingHappenedEventArgs eArg)
{
// QUESTION: COULD THE FOLLOWING LINE EVER RESULT IN A NULL
// REFERENCE EXCEPTION BECAUSE THE WORKER THREAD WAS
// INTERRUPTED TO HANDLE THE INCOMING EVENT WHILE EXECUTING
// Section X above ?????
int i = MemberString.Length;
}
}