By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,125 Members | 1,559 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,125 IT Pros & Developers. It's quick & easy.

Sinking Events and handling synchronization in a worker thread proc.

P: n/a
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;

}

}
Nov 17 '05 #1
Share this Question
Share on Google+
5 Replies


P: n/a
Hi Bill,

Welcome to MSDN newsgroup. From your description, you are wondering some
thread synchronization problems when a certain class object is accessed by
multi- thread, worker thread and event thread, yes?

Based on the pesudo code you provided, here are some of my understandings:

Generally, each workerthread will execute separately with no sense of other
threads. And when we fire an event which cause the event handler be called,
the event handler function will execute on the caller's thread. That means
, in your situation, if we create a workerItem one of whose methods is a
threadProc and another is a eventhandler, when the eventhandler is called
by a certain thread(other than the ThreadProc's exectuing thread), the
threadProc's executing thread won't be interrupted, it will always do it
own work(execute the code in the ThreadProc function).

And as for your following quesitn:

// 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 ?????
The answer is yes, it is surely possible that the "MemberString" will
return null. However, this is because the
MyClass object instance is shared between those two threads (ThreadProc 's
executing thread and MessageReceived/eventhandler's executing thread)
rather than the ThreadProc's thread being interrupted as you mentioned
early.

So to avoid this, we can simply add a lock on a certain reference object
when modiying the MemberString(or other data objects) and release the lock
after modified it. Also, in the eventhandler we also need to request the
lock so as to ensure we won't access that shared member concurrently. For
example:

=================================================
WorkerThreadProc()
{

// subscribe to some event from a 3rd-party library
AnObj.SomethingHappened += new
ObjectX.SomethingHappenedHandler(MessageReceived);

while (KeepGoing)
{
// syncObj is a class member of MyClass which can be any reference type
//set the lock flag
lock(syncObj)
{

MemberString = null;

Thread.Sleep(3000); //simulate othe operations

MemberString = "Joe";
}
Thread.Sleep(3000);
}

}

// event handler
void MessageReceived(object sender, SomethingHappenedEventArgs eArg)
{

lock(syncObj)
{
int i = MemberString.Length;

}

}

====================================

HTH. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #2

P: n/a
Thanks, Steven.

From below, it sounds like, however the event handler will always execute on
a thread (i.e.the thread of the event's source) separate from the local
thread that subscribed to the event (i.e. the 'sink' thread). Is that
correct? Is there ever a case where the source thread and sink thread would
be the same?

Bill
"Steven Cheng[MSFT]" <v-******@online.microsoft.com> wrote in message
news:XK**************@TK2MSFTNGXA03.phx.gbl...
Hi Bill,

Welcome to MSDN newsgroup. From your description, you are wondering some
thread synchronization problems when a certain class object is accessed by
multi- thread, worker thread and event thread, yes?

Based on the pesudo code you provided, here are some of my understandings:

Generally, each workerthread will execute separately with no sense of other threads. And when we fire an event which cause the event handler be called, the event handler function will execute on the caller's thread. That means
, in your situation, if we create a workerItem one of whose methods is a
threadProc and another is a eventhandler, when the eventhandler is called
by a certain thread(other than the ThreadProc's exectuing thread), the
threadProc's executing thread won't be interrupted, it will always do it
own work(execute the code in the ThreadProc function).

And as for your following quesitn:

// 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 ?????
The answer is yes, it is surely possible that the "MemberString" will
return null. However, this is because the
MyClass object instance is shared between those two threads (ThreadProc 's
executing thread and MessageReceived/eventhandler's executing thread)
rather than the ThreadProc's thread being interrupted as you mentioned
early.

So to avoid this, we can simply add a lock on a certain reference object
when modiying the MemberString(or other data objects) and release the lock
after modified it. Also, in the eventhandler we also need to request the
lock so as to ensure we won't access that shared member concurrently. For
example:

=================================================
WorkerThreadProc()
{

// subscribe to some event from a 3rd-party library
SomeObj AnObj = new SomeObj();
AnObj.SomethingHappened += new
ObjectX.SomethingHappenedHandler(MessageReceived);

while (KeepGoing)
{
// syncObj is a class member of MyClass which can be any reference type
//set the lock flag
lock(syncObj)
{

MemberString = null;

Thread.Sleep(3000); //simulate othe operations

MemberString = "Joe";
}
Thread.Sleep(3000);
}

}

// event handler
void MessageReceived(object sender, SomethingHappenedEventArgs eArg)
{

lock(syncObj)
{
int i = MemberString.Length;

}

}

====================================

HTH. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #3

P: n/a
Hi Bill,

Thanks for your followup.
I think the problem you're confusing about is the difference between the
..net 's event and win32 message event.

The .net event is an abstract concept and an event of a class is just as a
property of a class( a delegate) and other class instance call invoke a
certain class object's event in any thread(as long as it can access that
class object). Then, the event handler will be executed on the caller 's
thread. There is no "Source thread" conception in .net because there is
not need to exist a certain thread which do a message loop to listen for
any comming event message( like in win32 message system).
For example:

When we fire object A's event in thread B, if the event handler has a long
run task, only thread B will be blocked until the task to be finished.

Also, your concerns may exists in window form application since those
events of windows control/form is just encapsulating the WIN32 message
system. That means there is a certain "source thread" ( the main thread
which do the message loop for the windows form), then each winform
control/form's UI message will be encapsulated as an Event and the
Eventhandler will be executed at the Main thread of the windows form
application. (Main thread accept the message and invoke the proper
eventhandle according to that message). So in this case, the main thread
will block if the event handler has a long run task.

If you have any further questions , please feel free to post here. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #4

P: n/a
Steven:

Nice explanation. I was, indeed, confusing elements of the Win32 message
event system with C# delegates. Thanks for clearing it up.

Bill
"Steven Cheng[MSFT]" <v-******@online.microsoft.com> wrote in message
news:RH**************@TK2MSFTNGXA03.phx.gbl...
Hi Bill,

Thanks for your followup.
I think the problem you're confusing about is the difference between the
net 's event and win32 message event.

The .net event is an abstract concept and an event of a class is just as a property of a class( a delegate) and other class instance call invoke a
certain class object's event in any thread(as long as it can access that
class object). Then, the event handler will be executed on the caller 's
thread. There is no "Source thread" conception in .net because there is
not need to exist a certain thread which do a message loop to listen for
any comming event message( like in win32 message system).
For example:

When we fire object A's event in thread B, if the event handler has a long run task, only thread B will be blocked until the task to be finished.

Also, your concerns may exists in window form application since those
events of windows control/form is just encapsulating the WIN32 message
system. That means there is a certain "source thread" ( the main thread
which do the message loop for the windows form), then each winform
control/form's UI message will be encapsulated as an Event and the
Eventhandler will be executed at the Main thread of the windows form
application. (Main thread accept the message and invoke the proper
eventhandle according to that message). So in this case, the main thread
will block if the event handler has a long run task.

If you have any further questions , please feel free to post here. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #5

P: n/a
Thanks Bill,

I'm also glad that my suggestion has helped you.
Feel free to post here when you need any help next time :-)

Have a nice day!

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.