473,609 Members | 2,263 Online
Bytes | Software Development & Data Engineering Community
+ 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(WorkerTh readProc);
WorkerThread.St art();
}

WorkerThreadPro c()
{

// subscribe to some event from a 3rd-party library
AnObj.Something Happened += new
ObjectX.Somethi ngHappenedHandl er(MessageRecei ved);

while (KeepGoing)
{

// ************** Section X *************** **********
MemberString = null;
// do some stuff (maybe retreive a new value for MemberString
from DB)
// *************** *************** *************
MemberString = "Joe";

Thread.Sleep(50 00); // or perhaps an Event.WaitOne() call

}

}

// event handler
void MessageReceived (object sender, SomethingHappen edEventArgs 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.Le ngth;

}

}
Nov 17 '05 #1
5 2594
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 "MemberStri ng" 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:

=============== =============== =============== ====
WorkerThreadPro c()
{

// subscribe to some event from a 3rd-party library
AnObj.Something Happened += new
ObjectX.Somethi ngHappenedHandl er(MessageRecei ved);

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(30 00); //simulate othe operations

MemberString = "Joe";
}
Thread.Sleep(30 00);
}

}

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

lock(syncObj)
{
int i = MemberString.Le ngth;

}

}

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

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.m icrosoft.com> wrote in message
news:XK******** ******@TK2MSFTN GXA03.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 "MemberStri ng" 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:

=============== =============== =============== ====
WorkerThreadPro c()
{

// subscribe to some event from a 3rd-party library
SomeObj AnObj = new SomeObj();
AnObj.Something Happened += new
ObjectX.Somethi ngHappenedHandl er(MessageRecei ved);

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(30 00); //simulate othe operations

MemberString = "Joe";
}
Thread.Sleep(30 00);
}

}

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

lock(syncObj)
{
int i = MemberString.Le ngth;

}

}

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

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.m icrosoft.com> wrote in message
news:RH******** ******@TK2MSFTN GXA03.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
1413
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 two objects for sending of these events. The client opens tcp port 0 to receive events: if (ChannelServices.GetChannel("tcp") == null) {
3
506
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 to the main thread to be threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is: How can I NOT force those implementing my class to have to call...
1
2836
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 remote server and display this info on the UI. From doing some research, I know that the way my implementation works today is not thread-safe, because essentially my worker thread updates the UI, which is BAD. So, here I am trying to figure out how...
1
1779
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, 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...
3
14265
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 a working thread for processing the file, created a new FileSystemWatcher (as he said for real time processing), and then called the join method for the first thread. I can't really see the sence in this. Aren't the events of the...
1
2154
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 IE times out after a long time while stating opening from http://localhost:7765... I have a main thread that starts TCPListener and listens and accepts the connection and queues a worker thread to handle the socket transmission:
20
3951
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 SomeDelegateSignature foo2Event; { add { // some code here } remove { // some code here }
2
2825
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 invoked on the primary UI thread? Thanks, Jordan
15
2300
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 have read all about delegates, event handlers, Invoke methods etc, however they all seem to have undesribale side effects as I have tried them. The hardest part of the aplication is on exit, well I gues I could just
0
8121
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8062
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8559
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8208
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6987
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6050
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5506
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4010
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
1378
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.