473,770 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object initialization in C# thread - unexplained behaviour

Hello all,

I have a C# class (in this example, called A) that, in its
constructor, starts a thread with a method of its own. That thread
will be used to continuously check for one of its object's state and
generate classe's A events "Connected" and "Disconnect ed".

It looks something like this:

"
public class A
{
private AnotherObject an_obj;
private Thread thr;
...

public event System.EventHan dler Connected;
public event System.EventHan dler Disconnected;

public A()
{
thr = new Thread(new ThreadStart(thi s.DoThreadWork) );
thr.Start();
while (!thr.IsAlive);
thr.IsBackgroun d = true;
}

private void DoThreadWork()
{
an_obj = new AnotherObject() ;

while(true)
{
if (an_obj.IsPrese nt())
if (Connected != null)
Connected(this, EventArgs.Empty );
else
if (Disconnected != null)
Disconnected(th is, EventArgs.Empty );
}
}

public void DoSomethingX()
{
an_obj.CallXWor k();
}

public int DoSomethingY()
{
return an_obj.CallYWor k();
}
}
"

and a form that uses the previous class:

"
public class Form1: System.Windows. Forms.Form
{
private A objA;
...

public Form1()
{
objA = new SmartcardEVCont roller();

objA.Connected += new EventHandler(ob jA_Connected);
objA.Disconnect ed += new EventHandler(ob jA_Disconnected );
}

private void objA_Connected( object sender, EventArgs e)
{
objA.DoSomethin gX();
}

private void objA_Disconnect ed(object sender, EventArgs e)
{
int i = objA.DoSomethin gY();
MessageBox.Show ("Value: " + i);
}

private void button1_Click(o bject sender, System.EventArg s e)
{
objA.DoSomethin gX();
MessageBox.Show ("Done");
}
}
"
The problem is that although every call made to object "objA", inside
the "objA_Connected " or "objA_Disconnec ted" captured event works
perfectly fine, when a method is called on "objA" anywhere else it
just blocks the program execution. In this example, when button1 is
clicked, the instruction "MessageBox.Sho w("Done");" won't get called
and the program (Form1) will stop responding.

By the way, class AnotherObj is a .NET wrapper for a C dll that, in
turn, is a JNI wrapper for a Java class. All Java methods are
"synchroniz ed".

I thought that this could be a problem of the Java object but the fact
is that the cycle inside the thread keeps on executing when calls are
made inside "objA_Connected " or "objA_Disconnec ted" and those calls
execute successfully, no matter how many calls are made to object
"objA".
A strange thing that happens is that the call "objA.DoSomethi ngX();"
inside the click event makes the corresponding Java method start
executing (using log utilities in Java, I can check that the method
began execution but then stopped for no apparent reason).

The only thing I can now think of is that the thread that is spawned
in the A class has some kind of own memory space that the object that
was initialized inside the thread ("an_obj") can't be safely used
outside the thread. Being the thread that generates the events
"Connected" and "Disconnect ed", that could explain that calls to
object "objA", inside "objA_Connected " and "objA_Disconnec ted",
executed well. But that's only an hipothetical thought.

p.s.: I also tried initializing object "an_obj" outside the thread, in
classe's A contructor, but that way the call "an_obj.IsPrese nt())"
would also block in the C dll (that calls JNI code) for no apparent
reason.

If anyone could give me an explanation of why this is happening and
what I can do to avoid it, I would be grateful, as I can't figure it
out just by myself.

Thank you very much,
Ricardo Pereira
Nov 16 '05
12 2332
I agree, while loop is unnecessary. IsBackground = true could be done from
inside DoThreadWork method. Which will be a bit simpler than signalling.

HTH
Alex

"TT (Tom Tempelaere)" <_N_0SPA|/\|t*******@hotm ail.com|/\|APS0_N_> wrote in
message news:8k******** **************@ phobos.telenet-ops.be...
"Ricardo Pereira" <pe*********@ma il.telepac.pt> wrote in message
news:f1******** *************** **@posting.goog le.com...
Hello all,

I have a C# class (in this example, called A) that, in its
constructor, starts a thread with a method of its own. That thread
will be used to continuously check for one of its object's state and
generate classe's A events "Connected" and "Disconnect ed".

It looks something like this: [...]
public A()
{
thr = new Thread(new ThreadStart(thi s.DoThreadWork) );
thr.Start();
while (!thr.IsAlive);
thr.IsBackgroun d = true;
}

[...]

It is better not to poll like you do in the while loop. It is better to

use a ManualResetEven t object and wait (WaitHandle.Wai tOne) on it for the thread to come alive. Let the thread you start signal the event when it starts
(ManualResetEve nt.Set).

Cheers,
---
Tom Tempelaere

Nov 16 '05 #11
AlexS <sa***********@ SPAMsympaticoPL EASE.ca> wrote:
I agree, while loop is unnecessary. IsBackground = true could be done from
inside DoThreadWork method. Which will be a bit simpler than signalling.


Or it could just be done before the thread is started, which is even
simpler and more logical (from my point of view) as it makes sense to
me to set up everything to do with the thread (name, background,
priority etc) before starting it.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12
That, you are absolutely correct.
I had already had that changed.

Thanks again,
Ricardo Pereira
Nov 16 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

106
5609
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an initalisation list for initialising data members of a class?
2
2979
by: Ryan Mitchley | last post by:
Hi all I have code for an object factory, heavily based on an article by Jim Hyslop (although I've made minor modifications). The factory was working fine using g++, but since switching to the Intel compiler it has stopped working. I think the singleton pattern static instance thing may be at the root of the problem, but I'm not sure. I had to add calls to instance() in regCreateFn, which gets the behaviour more in line with what I was...
4
2674
by: Cheng Mo | last post by:
I know global varaibles should always be avoided. I asked this question just for deep insight about C++. If global variables are distributed among different source code files, what's the initialziation sequence of these varaibles. Say, Foo g_fooMain in main.cpp; Foo g_hello in hello.cpp; Foo g_bye in bye.cpp; and main.cpp has code #include "hello.h"
8
1840
by: Mark Neilson | last post by:
1. What is the best way to make a single instance of my top level class (DLL) internally available to all other members of the assembly? The top level object is where all other access is made in to the program. Where and how do I declare and initialise this object? For instance, it would have property implementation like this: //******************************************* public MyClass1 Class1 {
4
5021
by: 6tc1 | last post by:
Hi all, I have just finished debugging a windows application and have solved the problem - however, I want to be sure that I understand the problem before I move on. Before I detail the problem, this problem requires some understanding of threading concepts. Basically, the class contained both a PictureBox object as well as a corresponding Image object (they both had a copy of the same picture). The following was used to access the...
26
5694
by: yb | last post by:
Hi, Is there a standard for the global 'window' object in browsers? For example, it supports methods such as setInterval and clearInterval, and several others. I know that w3c standardized several parts of the DOM, but this does not include the window object. Thank you
1
4244
by: philwozza | last post by:
Hi I have a THREAD class that uses the static variable NextThreadID to store the id of the next thread to be created and a static Mutex to protect it. class THREAD { public: int Start(void); private: unsigned int ThreadID;
9
2473
by: ziman137 | last post by:
Hi all, The results from following codes got me a bit confused. #include <stdio.h> #include <iostream> using namespace std; struct A {
23
3149
by: tonytech08 | last post by:
What I like about the C++ object model: that the data portion of the class IS the object (dereferencing an object gets you the data of a POD object). What I don't like about the C++ object model: that most OO features are not available for class object design without loss of POD-ness. So, I'm more than leaning toward "bad" because of the limitations and
0
9454
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
10101
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
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
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8933
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
7456
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
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.