Calling methods from constructor?

G

Grandma Wilkerson

Hi,

I have a class whose constructor accepts a Socket as an argument. The
constructor then makes a call to Socket.BeginReceive(). The callback
delegate passed to BeginReceive() is a method of my class. There is a slight
chance that the callback delegate will be called from the I/O thread pool
BEFORE my constructor completes. Is calling this delegate before the
constructor finishes a problem?

In C++, this type of arrangement was a problem as I recall. In C#, it
doesn't seem like it SHOULD be a problem. After all, I can call private
methods from my constructor so why shouldn't some external party be able to
call them in the midst of construction as well? In any case, I just wanted
to double-check!

Granny
 
W

William Stacey

To side-step this issue and possible others, you could (of course) create
..Send() public method or .Connect() and use that after construction. You
can still set the socket var in your constructor and/or property of the
class.
--wjs
 
J

Jon Skeet

Grandma Wilkerson said:
I have a class whose constructor accepts a Socket as an argument. The
constructor then makes a call to Socket.BeginReceive(). The callback
delegate passed to BeginReceive() is a method of my class. There is a slight
chance that the callback delegate will be called from the I/O thread pool
BEFORE my constructor completes. Is calling this delegate before the
constructor finishes a problem?

Well, it'll be a potential problem if the delegate relies on
information which is set up after Socket.BeginReceive() is called, but
I don't think it's fundamentally a problem. Probably worth documenting
very clearly though, for maintenance purposes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top