473,465 Members | 1,405 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Sinking Events and handling synchronization in a worker thread proc.

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
5 2584
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Efim | last post by:
Hi, I have got some problem with sending of events in .NET. I am using remouting. The client has got 2 objects for receiving different types of events (responses and events) The server has got...
3
by: Jacob | last post by:
I'm working on a class that needs to be called from a windows form, do it's work, and then, show progress back to the main form. I'm well aware that worker threads need to call Invoke for updates...
1
by: Natalia DeBow | last post by:
Hi, I am working on a Windows-based client-server application. I am involved in the development of the remote client modules. I am using asynchronous delegates to obtain information from...
1
by: Bill Davidson | last post by:
(RESEND: I added a little more code to the sample for clarity) Hello All: I've got a question about synchronization requiremements in a C# worker thread procedure that, among other things,...
3
by: Stampede | last post by:
Hi, I want to use the FileSystemWatcher in a Windows Service. I read an article, where the author created the FileSystemWatcher object in a seperate thread and when the event is fired, he started...
1
by: Laura T. | last post by:
Hi, I've this kind a program, using sockets to communicate with the clients. One of the clients can be a web browser (like IE). When using IE as a client, the transmission blocks completely, and...
20
by: David Levine | last post by:
I ran into a problem this morning with event accessor methods that appears to be a bug in C# and I am wondering if this a known issue. public event SomeDelegateSignature fooEvent; public event...
2
by: Jordan | last post by:
I need to handle UI events in a worker thread instead of the primary UI thread. In C#, is the normal UI event handling behavior to run in a context thread on the thread pool or are events always...
15
by: colin | last post by:
Hi, Im familiar with c,c++ etc, and Ive spent a week trying to write my first app in c# it works reasonably well, but im having difficulty getting to grips with inter thread signalling etc. I...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.