473,320 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

BeginAccept callback problem

Hi all,

I'm trying to develop a server that listens to incoming calls using
the asycnhronous methods BeginAccept / EndAccept. I start the server
(till this point it is ok) and few seconds later I stop it (with no
clients connected). Once I press the stop button an
ObjectDisposedException is fired. What is the reason for this? Is it
because the thread is still running even after I closed the server
socket? Here is the code:

private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
mniStart.Enabled = false;
btnStop.Enabled = true;
mniStop.Enabled = true;

try
{
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void btnStop_Click(object sender, EventArgs e)
{
btnStop.Enabled = false;
mniStop.Enabled = false;
btnStart.Enabled = true;
mniStart.Enabled = true;

try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}

Thanks in advance for your help,
Clayton

Apr 10 '07 #1
10 4415
On 10 Apr, 08:14, "Clayton" <clayton.cu...@gmail.comwrote:
Hi all,

I'm trying to develop a server that listens to incoming calls using
the asycnhronous methods BeginAccept / EndAccept. I start the server
(till this point it is ok) and few seconds later I stop it (with no
clients connected). Once I press the stop button an
ObjectDisposedException is fired. What is the reason for this? Is it
because the thread is still running even after I closed the server
socket? Here is the code:

private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
mniStart.Enabled = false;
btnStop.Enabled = true;
mniStop.Enabled = true;

try
{
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void btnStop_Click(object sender, EventArgs e)
{
btnStop.Enabled = false;
mniStop.Enabled = false;
btnStart.Enabled = true;
mniStart.Enabled = true;

try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}

Thanks in advance for your help,
Clayton
Hi, solution is at the bottom of this version. For reference this
version compiles. It's always best to create a sample that compiles
and shows the exact problem. I've also made a couple of little changes
like moving the button state code into the try blocks. As you had it
on an error the buttons would be in an unusable state. Anyway paste it
into an empty forms solution and watch out for line breaks. To skip
straight to the solution just look for Solved :)

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;

namespace WindowsApplication15
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;

private System.Net.Sockets.Socket sListener = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
private System.Windows.Forms.Label lblStatus;

private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(48, 80);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "start";
this.btnStart.Click += new
System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(56, 120);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 1;
this.btnStop.Text = "stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// lblStatus
//
this.lblStatus.Location = new System.Drawing.Point(64, 160);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 2;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void btnStart_Click(object sender, EventArgs e)
{
SocketPermission perm = new
SocketPermission(System.Security.Permissions.Permi ssionState.Unrestricted);
IPEndPoint ep = new
System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1") ,3456);
try
{
sListener.Bind(ep);
sListener.Listen(5);
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
btnStop.Enabled = false;
btnStart.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler;
try
{
sHandler = listener.EndAccept(ar);
//<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException)
{
Console.WriteLine("Solved");
}
}

}
}

Apr 10 '07 #2
Clayton, your solution does not prevent the exception from being raised.
The 'Can't access disposed object' can occur not just in EndAccept(), but
also in EndReceive(). Oddly, under the Win32 Asynchronous Socket model
(WSAAsyncSelect() ) the 'disposed object' exception in correct code never
happens.

Michael

"DeveloperX" <nn*****@operamail.comwrote in message
news:11*********************@q75g2000hsh.googlegro ups.com...
On 10 Apr, 08:14, "Clayton" <clayton.cu...@gmail.comwrote:
>Hi all,

I'm trying to develop a server that listens to incoming calls using
the asycnhronous methods BeginAccept / EndAccept. I start the server
(till this point it is ok) and few seconds later I stop it (with no
clients connected). Once I press the stop button an
ObjectDisposedException is fired. What is the reason for this? Is it
because the thread is still running even after I closed the server
socket? Here is the code:

private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
mniStart.Enabled = false;
btnStop.Enabled = true;
mniStop.Enabled = true;

try
{
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void btnStop_Click(object sender, EventArgs e)
{
btnStop.Enabled = false;
mniStop.Enabled = false;
btnStart.Enabled = true;
mniStart.Enabled = true;

try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}

Thanks in advance for your help,
Clayton

Hi, solution is at the bottom of this version. For reference this
version compiles. It's always best to create a sample that compiles
and shows the exact problem. I've also made a couple of little changes
like moving the button state code into the try blocks. As you had it
on an error the buttons would be in an unusable state. Anyway paste it
into an empty forms solution and watch out for line breaks. To skip
straight to the solution just look for Solved :)

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;

namespace WindowsApplication15
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;

private System.Net.Sockets.Socket sListener = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
private System.Windows.Forms.Label lblStatus;

private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(48, 80);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "start";
this.btnStart.Click += new
System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(56, 120);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 1;
this.btnStop.Text = "stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// lblStatus
//
this.lblStatus.Location = new System.Drawing.Point(64, 160);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 2;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void btnStart_Click(object sender, EventArgs e)
{
SocketPermission perm = new
SocketPermission(System.Security.Permissions.Permi ssionState.Unrestricted);
IPEndPoint ep = new
System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1") ,3456);
try
{
sListener.Bind(ep);
sListener.Listen(5);
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
btnStop.Enabled = false;
btnStart.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler;
try
{
sHandler = listener.EndAccept(ar);
//<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException)
{
Console.WriteLine("Solved");
}
}

}
}

Apr 10 '07 #3
On 10 Apr, 14:54, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:
Clayton, your solution does not prevent the exception from being raised.
The 'Can't access disposed object' can occur not just in EndAccept(), but
also in EndReceive(). Oddly, under the Win32 Asynchronous Socket model
(WSAAsyncSelect() ) the 'disposed object' exception in correct code never
happens.

Michael

"DeveloperX" <nntp...@operamail.comwrote in message

news:11*********************@q75g2000hsh.googlegro ups.com...
On 10 Apr, 08:14, "Clayton" <clayton.cu...@gmail.comwrote:
Hi all,
I'm trying to develop a server that listens to incoming calls using
the asycnhronous methods BeginAccept / EndAccept. I start the server
(till this point it is ok) and few seconds later I stop it (with no
clients connected). Once I press the stop button an
ObjectDisposedException is fired. What is the reason for this? Is it
because the thread is still running even after I closed the server
socket? Here is the code:
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
mniStart.Enabled = false;
btnStop.Enabled = true;
mniStop.Enabled = true;
try
{
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
btnStop.Enabled = false;
mniStop.Enabled = false;
btnStart.Enabled = true;
mniStart.Enabled = true;
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here
MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
Thanks in advance for your help,
Clayton
Hi, solution is at the bottom of this version. For reference this
version compiles. It's always best to create a sample that compiles
and shows the exact problem. I've also made a couple of little changes
like moving the button state code into the try blocks. As you had it
on an error the buttons would be in an unusable state. Anyway paste it
into an empty forms solution and watch out for line breaks. To skip
straight to the solution just look for Solved :)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
namespace WindowsApplication15
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Net.Sockets.Socket sListener = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
private System.Windows.Forms.Label lblStatus;
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(48, 80);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "start";
this.btnStart.Click += new
System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(56, 120);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 1;
this.btnStop.Text = "stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// lblStatus
//
this.lblStatus.Location = new System.Drawing.Point(64, 160);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 2;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnStart_Click(object sender, EventArgs e)
{
SocketPermission perm = new
SocketPermission(System.Security.Permissions.Permi ssionState.Unrestricted);
IPEndPoint ep = new
System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1") ,3456);
try
{
sListener.Bind(ep);
sListener.Listen(5);
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
btnStop.Enabled = false;
btnStart.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler;
try
{
sHandler = listener.EndAccept(ar);
//<---------------Exception fired here
MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException)
{
Console.WriteLine("Solved");
}
}
}
}- Hide quoted text -

- Show quoted text -
Hi, no send or receive code was provided so I didn't look at that.
Just to clarify though is there a way under the framework to avoid
this happening? I see the pattern I've presented above all over the
place.
Cheers

Apr 11 '07 #4
The situation described by Mike is guaranteed to raise an exception in
AcceptCallback() when the server socket is closed.
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
If the server socket is closed before any client connection is established,
then there is no point in showing Receive or Send code.
It is quite easy to work around by try/catch (as Mike does and you suggest
too) or by setting up a flag that would be raised to 'true' in BeginAccept()
and made 'false' when the program code closes the listener socket, and check
that flag in AcceptCallback before going any further. I consider this to be
a flaw since I couldn't find anything on MSDN that would confirm or justify
this behavior.

Michael

"DeveloperX" <nn*****@operamail.comwrote in message
news:11**********************@e65g2000hsc.googlegr oups.com...
On 10 Apr, 14:54, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:
Clayton, your solution does not prevent the exception from being
raised.
The 'Can't access disposed object' can occur not just in EndAccept(), but
also in EndReceive(). Oddly, under the Win32 Asynchronous Socket model
(WSAAsyncSelect() ) the 'disposed object' exception in correct code never
happens.

Michael

"DeveloperX" <nntp...@operamail.comwrote in message

news:11*********************@q75g2000hsh.googlegro ups.com...
On 10 Apr, 08:14, "Clayton" <clayton.cu...@gmail.comwrote:
Hi all,
I'm trying to develop a server that listens to incoming calls using
the asycnhronous methods BeginAccept / EndAccept. I start the server
(till this point it is ok) and few seconds later I stop it (with no
clients connected). Once I press the stop button an
ObjectDisposedException is fired. What is the reason for this? Is it
because the thread is still running even after I closed the server
socket? Here is the code:
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
mniStart.Enabled = false;
btnStop.Enabled = true;
mniStop.Enabled = true;
try
{
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
btnStop.Enabled = false;
mniStop.Enabled = false;
btnStart.Enabled = true;
mniStart.Enabled = true;
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here
MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
Thanks in advance for your help,
Clayton
Hi, solution is at the bottom of this version. For reference this
version compiles. It's always best to create a sample that compiles
and shows the exact problem. I've also made a couple of little changes
like moving the button state code into the try blocks. As you had it
on an error the buttons would be in an unusable state. Anyway paste it
into an empty forms solution and watch out for line breaks. To skip
straight to the solution just look for Solved :)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
namespace WindowsApplication15
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Net.Sockets.Socket sListener = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
private System.Windows.Forms.Label lblStatus;
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(48, 80);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "start";
this.btnStart.Click += new
System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(56, 120);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 1;
this.btnStop.Text = "stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// lblStatus
//
this.lblStatus.Location = new System.Drawing.Point(64, 160);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 2;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnStart_Click(object sender, EventArgs e)
{
SocketPermission perm = new
SocketPermission(System.Security.Permissions.Permi ssionState.Unrestricted);
IPEndPoint ep = new
System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1") ,3456);
try
{
sListener.Bind(ep);
sListener.Listen(5);
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
btnStop.Enabled = false;
btnStart.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler;
try
{
sHandler = listener.EndAccept(ar);
//<---------------Exception fired here
MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException)
{
Console.WriteLine("Solved");
}
}
}
}- Hide quoted text -

- Show quoted text -
Hi, no send or receive code was provided so I didn't look at that.
Just to clarify though is there a way under the framework to avoid
this happening? I see the pattern I've presented above all over the
place.
Cheers
Apr 11 '07 #5
On 11 Apr, 14:58, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:
The situation described by Mike is guaranteed to raise an exception in
AcceptCallback() when the server socket is closed.
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
If the server socket is closed before any client connection is established,
then there is no point in showing Receive or Send code.
It is quite easy to work around by try/catch (as Mike does and you suggest
too) or by setting up a flag that would be raised to 'true' in BeginAccept()
and made 'false' when the program code closes the listener socket, and check
that flag in AcceptCallback before going any further. I consider this to be
a flaw since I couldn't find anything on MSDN that would confirm or justify
this behavior.

Michael

"DeveloperX" <nntp...@operamail.comwrote in message

news:11**********************@e65g2000hsc.googlegr oups.com...
On 10 Apr, 14:54, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:


Clayton, your solution does not prevent the exception from being
raised.
The 'Can't access disposed object' can occur not just in EndAccept(), but
also in EndReceive(). Oddly, under the Win32 Asynchronous Socket model
(WSAAsyncSelect() ) the 'disposed object' exception in correct code never
happens.
Michael
"DeveloperX" <nntp...@operamail.comwrote in message
news:11*********************@q75g2000hsh.googlegro ups.com...
On 10 Apr, 08:14, "Clayton" <clayton.cu...@gmail.comwrote:
>Hi all,
>I'm trying to develop a server that listens to incoming calls using
>the asycnhronous methods BeginAccept / EndAccept. I start the server
>(till this point it is ok) and few seconds later I stop it (with no
>clients connected). Once I press the stop button an
>ObjectDisposedException is fired. What is the reason for this? Is it
>because the thread is still running even after I closed the server
>socket? Here is the code:
>private void btnStart_Click(object sender, EventArgs e)
> {
> btnStart.Enabled = false;
> mniStart.Enabled = false;
> btnStop.Enabled = true;
> mniStop.Enabled = true;
> try
> {
> sListener.BeginAccept(new
>AsyncCallback(AcceptCallback), sListener);
> lblStatus.Text = "Waiting for a connection...";
> }
> catch (SocketException se)
> {
> MessageBox.Show(se.Message, "VEP Server Error",
>MessageBoxButtons.OK, MessageBoxIcon.Error);
> }
> }
> private void btnStop_Click(object sender, EventArgs e)
> {
> btnStop.Enabled = false;
> mniStop.Enabled = false;
> btnStart.Enabled = true;
> mniStart.Enabled = true;
> try
> {
> lblStatus.Text = "Stopped";
> //sListener.Shutdown(SocketShutdown.Both);
> sListener.Close();
> }
> catch (SocketException se)
> {
> MessageBox.Show(se.Message, "VEP Server Error",
>MessageBoxButtons.OK, MessageBoxIcon.Error);
> }
> }
> private void AcceptCallback(IAsyncResult ar)
> {
> Socket listener = (Socket)ar.AsyncState;
> Socket sHandler = listener.EndAccept(ar);
><---------------Exception fired here
> MessageBox.Show("Connected with " +
>sHandler.RemoteEndPoint.ToString());
> }
>Thanks in advance for your help,
>Clayton
Hi, solution is at the bottom of this version. For reference this
version compiles. It's always best to create a sample that compiles
and shows the exact problem. I've also made a couple of little changes
like moving the button state code into the try blocks. As you had it
on an error the buttons would be in an unusable state. Anyway paste it
into an empty forms solution and watch out for line breaks. To skip
straight to the solution just look for Solved :)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
namespace WindowsApplication15
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Net.Sockets.Socket sListener = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
private System.Windows.Forms.Label lblStatus;
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(48, 80);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "start";
this.btnStart.Click += new
System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(56, 120);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 1;
this.btnStop.Text = "stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// lblStatus
//
this.lblStatus.Location = new System.Drawing.Point(64, 160);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 2;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnStart_Click(object sender, EventArgs e)
{
SocketPermission perm = new
SocketPermission(System.Security.Permissions.Permi ssionState.Unrestricted);
IPEndPoint ep = new
System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1") ,3456);
try
{
sListener.Bind(ep);
sListener.Listen(5);
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
btnStop.Enabled = false;
btnStart.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler;
try
{
sHandler = listener.EndAccept(ar);
//<---------------Exception fired here
MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException)
{
Console.WriteLine("Solved");
}
}
}
}- Hide quoted text -
- Show quoted text -

Hi, no send or receive code was provided so I didn't look at that.
Just to clarify though is there a way under the framework to avoid
this happening? I see the pattern I've presented above all over the
place.
Cheers- Hide quoted text -

- Show quoted text -
I did consider the flag option, but decided against it as I've seen
the other pattern used.
I disassembed the System.Net.Sockets.Socket after posting this and I
think I've sussed it. Here you go.

public void Close()
{
((IDisposable) this).Dispose();
}
So Closing the socket doesn't close it it disposes of it. Nested in
Dispose we have

int num = UnsafeNclNativeMethods.OSSOCK.closesocket(this.m_H andle);

In pretty much every IO method the first few lines are always:

if (this.CleanedUp)
{
throw new ObjectDisposedException(base.GetType().FullName);
}
Interestingly also in Dispose it does
if (disposing)
{
try
{
asyncEvent.Set();
where asyncEvent is a refererence to a member variable of type
ManualResetEvent. This is created in another method just before the
unsafe method call and seems purely related to tidying up some bits
and pieces first.

So it seems to be by design. That's the Framework 1.1 disassembly,
can't check 2 here.
Both Close and Dispose could be overriden in a derived Socket class I
guess to give the user a chance to tidy up their code, or wrap up the
socket code and go with the flag option you mentioned, or use the
DisposeException. The more I think about it I'd probably go with
wrapping all the socket code into a class and going with the flag and
obscuring access to the actual Socket's Close method.

Interesting stuff.

Apr 11 '07 #6
Adding a flag will work with exception on EndAccept() because you know when
you close the listener socket. In other Callbacks where you have to issue
EndReceive() there is no way of predicting when the handler socket gets
disposed when something happens on the other side of the connection. I also
don't see how a protected method Dispose() could be overridden in a derived
class, or for that matter overriding the (non-virtual) Socket.Close().

Michael

"DeveloperX" <nn*****@operamail.comwrote in message
news:11**********************@l77g2000hsb.googlegr oups.com...
On 11 Apr, 14:58, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:
The situation described by Mike is guaranteed to raise an exception in
AcceptCallback() when the server socket is closed.
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler = listener.EndAccept(ar);
<---------------Exception fired here

MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
If the server socket is closed before any client connection is
established,
then there is no point in showing Receive or Send code.
It is quite easy to work around by try/catch (as Mike does and you
suggest
too) or by setting up a flag that would be raised to 'true' in
BeginAccept()
and made 'false' when the program code closes the listener socket, and
check
that flag in AcceptCallback before going any further. I consider this to
be
a flaw since I couldn't find anything on MSDN that would confirm or
justify
this behavior.

Michael

"DeveloperX" <nntp...@operamail.comwrote in message

news:11**********************@e65g2000hsc.googlegr oups.com...
On 10 Apr, 14:54, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:


Clayton, your solution does not prevent the exception from being
raised.
The 'Can't access disposed object' can occur not just in EndAccept(),
but
also in EndReceive(). Oddly, under the Win32 Asynchronous Socket model
(WSAAsyncSelect() ) the 'disposed object' exception in correct code
never
happens.
Michael
"DeveloperX" <nntp...@operamail.comwrote in message
news:11*********************@q75g2000hsh.googlegro ups.com...
On 10 Apr, 08:14, "Clayton" <clayton.cu...@gmail.comwrote:
>Hi all,
>I'm trying to develop a server that listens to incoming calls using
>the asycnhronous methods BeginAccept / EndAccept. I start the server
>(till this point it is ok) and few seconds later I stop it (with no
>clients connected). Once I press the stop button an
>ObjectDisposedException is fired. What is the reason for this? Is it
>because the thread is still running even after I closed the server
>socket? Here is the code:
>private void btnStart_Click(object sender, EventArgs e)
> {
> btnStart.Enabled = false;
> mniStart.Enabled = false;
> btnStop.Enabled = true;
> mniStop.Enabled = true;
> try
> {
> sListener.BeginAccept(new
>AsyncCallback(AcceptCallback), sListener);
> lblStatus.Text = "Waiting for a connection...";
> }
> catch (SocketException se)
> {
> MessageBox.Show(se.Message, "VEP Server Error",
>MessageBoxButtons.OK, MessageBoxIcon.Error);
> }
> }
> private void btnStop_Click(object sender, EventArgs e)
> {
> btnStop.Enabled = false;
> mniStop.Enabled = false;
> btnStart.Enabled = true;
> mniStart.Enabled = true;
> try
> {
> lblStatus.Text = "Stopped";
> //sListener.Shutdown(SocketShutdown.Both);
> sListener.Close();
> }
> catch (SocketException se)
> {
> MessageBox.Show(se.Message, "VEP Server Error",
>MessageBoxButtons.OK, MessageBoxIcon.Error);
> }
> }
> private void AcceptCallback(IAsyncResult ar)
> {
> Socket listener = (Socket)ar.AsyncState;
> Socket sHandler = listener.EndAccept(ar);
><---------------Exception fired here
> MessageBox.Show("Connected with " +
>sHandler.RemoteEndPoint.ToString());
> }
>Thanks in advance for your help,
>Clayton
Hi, solution is at the bottom of this version. For reference this
version compiles. It's always best to create a sample that compiles
and shows the exact problem. I've also made a couple of little changes
like moving the button state code into the try blocks. As you had it
on an error the buttons would be in an unusable state. Anyway paste it
into an empty forms solution and watch out for line breaks. To skip
straight to the solution just look for Solved :)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
namespace WindowsApplication15
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Net.Sockets.Socket sListener = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
private System.Windows.Forms.Label lblStatus;
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(48, 80);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "start";
this.btnStart.Click += new
System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(56, 120);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 1;
this.btnStop.Text = "stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// lblStatus
//
this.lblStatus.Location = new System.Drawing.Point(64, 160);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 2;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnStart_Click(object sender, EventArgs e)
{
SocketPermission perm = new
SocketPermission(System.Security.Permissions.Permi ssionState.Unrestricted);
IPEndPoint ep = new
System.Net.IPEndPoint(IPAddress.Parse("127.0.0.1") ,3456);
try
{
sListener.Bind(ep);
sListener.Listen(5);
sListener.BeginAccept(new
AsyncCallback(AcceptCallback), sListener);
lblStatus.Text = "Waiting for a connection...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
lblStatus.Text = "Stopped";
//sListener.Shutdown(SocketShutdown.Both);
sListener.Close();
btnStop.Enabled = false;
btnStart.Enabled = true;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "VEP Server Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket sHandler;
try
{
sHandler = listener.EndAccept(ar);
//<---------------Exception fired here
MessageBox.Show("Connected with " +
sHandler.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException)
{
Console.WriteLine("Solved");
}
}
}
}- Hide quoted text -
- Show quoted text -

Hi, no send or receive code was provided so I didn't look at that.
Just to clarify though is there a way under the framework to avoid
this happening? I see the pattern I've presented above all over the
place.
Cheers- Hide quoted text -

- Show quoted text -
I did consider the flag option, but decided against it as I've seen
the other pattern used.
I disassembed the System.Net.Sockets.Socket after posting this and I
think I've sussed it. Here you go.

public void Close()
{
((IDisposable) this).Dispose();
}
So Closing the socket doesn't close it it disposes of it. Nested in
Dispose we have

int num = UnsafeNclNativeMethods.OSSOCK.closesocket(this.m_H andle);

In pretty much every IO method the first few lines are always:

if (this.CleanedUp)
{
throw new ObjectDisposedException(base.GetType().FullName);
}
Interestingly also in Dispose it does
if (disposing)
{
try
{
asyncEvent.Set();
where asyncEvent is a refererence to a member variable of type
ManualResetEvent. This is created in another method just before the
unsafe method call and seems purely related to tidying up some bits
and pieces first.

So it seems to be by design. That's the Framework 1.1 disassembly,
can't check 2 here.
Both Close and Dispose could be overriden in a derived Socket class I
guess to give the user a chance to tidy up their code, or wrap up the
socket code and go with the flag option you mentioned, or use the
DisposeException. The more I think about it I'd probably go with
wrapping all the socket code into a class and going with the flag and
obscuring access to the actual Socket's Close method.

Interesting stuff.
Apr 11 '07 #7
Adding a flag will work with exception on EndAccept() because you know when
you close the listener socket. In other Callbacks where you have to issue
EndReceive() there is no way of predicting when the handler socket gets
disposed when something happens on the other side of the connection. I also
don't see how a protected method Dispose() could be overridden in a derived
class, or for that matter overriding the (non-virtual) Socket.Close().
That's useful to know. I'll have to check why I thought Close could be
overridden I could of sworn it was virtual, again 1.1, I'm back on 2
now but I can't imagine that would change. I don't understand what you
mean regarding to Dispose, have I missed something obvious?

This compiles:

class Socket2 : System.Net.Sockets.Socket
{
public Socket2(AddressFamily af, SocketType st, ProtocolType
pt) : base(af,st,pt)
{
}
protected override void Dispose(Boolean v)
{
Console.WriteLine("test");
base.Dispose(v);
}
}

Test is printed when I do

Socket2 s = new Socket2(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
using (s)
{
Console.WriteLine(".");
}
(silly example I know, but just trying to understand what you mean)

Cheers

Apr 11 '07 #8
You are right, it compiles and works. I didn't mean much. The
documentation says 'override' keyword can be used only on static or virtual
methods. Well, there is another place in help that says that protected
members can be overridden in derived classes. I'll take a another look, may
be there is a way of 'knowing' the socket is disposed by wrapping the socket
within a state object. The socket then would tell the 'owner' object that it
is about to 'bite the dust' and since state objects should be used in
callbacks anyway it should be possible to determine whether the socket is
disposed. Triggering an event or would even better. I'll give it a try.
Thanks for the idea.

Michael

"DeveloperX" <nn*****@operamail.comwrote in message
news:11**********************@y5g2000hsa.googlegro ups.com...
>Adding a flag will work with exception on EndAccept() because you know
when
you close the listener socket. In other Callbacks where you have to issue
EndReceive() there is no way of predicting when the handler socket gets
disposed when something happens on the other side of the connection. I
also
don't see how a protected method Dispose() could be overridden in a
derived
class, or for that matter overriding the (non-virtual) Socket.Close().

That's useful to know. I'll have to check why I thought Close could be
overridden I could of sworn it was virtual, again 1.1, I'm back on 2
now but I can't imagine that would change. I don't understand what you
mean regarding to Dispose, have I missed something obvious?

This compiles:

class Socket2 : System.Net.Sockets.Socket
{
public Socket2(AddressFamily af, SocketType st, ProtocolType
pt) : base(af,st,pt)
{
}
protected override void Dispose(Boolean v)
{
Console.WriteLine("test");
base.Dispose(v);
}
}

Test is printed when I do

Socket2 s = new Socket2(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
using (s)
{
Console.WriteLine(".");
}
(silly example I know, but just trying to understand what you mean)

Cheers

Apr 12 '07 #9
On 12 Apr, 02:19, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:
You are right, it compiles and works. I didn't mean much. The
documentation says 'override' keyword can be used only on static or virtual
methods. Well, there is another place in help that says that protected
members can be overridden in derived classes. I'll take a another look, may
be there is a way of 'knowing' the socket is disposed by wrapping the socket
within a state object. The socket then would tell the 'owner' object thatit
is about to 'bite the dust' and since state objects should be used in
callbacks anyway it should be possible to determine whether the socket is
disposed. Triggering an event or would even better. I'll give it a try.
Thanks for the idea.

Michael

"DeveloperX" <nntp...@operamail.comwrote in message

news:11**********************@y5g2000hsa.googlegro ups.com...
Adding a flag will work with exception on EndAccept() because you know
when
you close the listener socket. In other Callbacks where you have to issue
EndReceive() there is no way of predicting when the handler socket gets
disposed when something happens on the other side of the connection. I
also
don't see how a protected method Dispose() could be overridden in a
derived
class, or for that matter overriding the (non-virtual) Socket.Close().
That's useful to know. I'll have to check why I thought Close could be
overridden I could of sworn it was virtual, again 1.1, I'm back on 2
now but I can't imagine that would change. I don't understand what you
mean regarding to Dispose, have I missed something obvious?
This compiles:
class Socket2 : System.Net.Sockets.Socket
{
public Socket2(AddressFamily af, SocketType st, ProtocolType
pt) : base(af,st,pt)
{
}
protected override void Dispose(Boolean v)
{
Console.WriteLine("test");
base.Dispose(v);
}
}
Test is printed when I do
Socket2 s = new Socket2(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
using (s)
{
Console.WriteLine(".");
}
(silly example I know, but just trying to understand what you mean)
Cheers- Hide quoted text -

- Show quoted text -
Aah good stuff, yes I like the wrapper idea, it's certainly the
cleanest I think. Cheers Michael.

Apr 12 '07 #10
Well, the wrapper idea is a dead end. The listener socket can be
sub-classed and 'wrapped' because it is created by the application code. Not
much of gain since the program code 'knows' when it closes the listener. The
handler socket returned by EndAccept() or EndReceive() is class Socket and
will dispose itself 'in silence', poor thing. There is no way, I am aware
of, getting notification when the handler socket gets disposed. In that
sense, Win32 asynchronous socket model behaves better - no matter how the
handler socket was closed, the window registered in WSAAsyncSelect() gets
notification.

Michael

"DeveloperX" <nn*****@operamail.comwrote in message
news:11*********************@o5g2000hsb.googlegrou ps.com...
On 12 Apr, 02:19, "Michael Rubinstein" <mSPAM_REMOVEr@mŽubinstein.com>
wrote:
You are right, it compiles and works. I didn't mean much. The
documentation says 'override' keyword can be used only on static or
virtual
methods. Well, there is another place in help that says that protected
members can be overridden in derived classes. I'll take a another look,
may
be there is a way of 'knowing' the socket is disposed by wrapping the
socket
within a state object. The socket then would tell the 'owner' object that
it
is about to 'bite the dust' and since state objects should be used in
callbacks anyway it should be possible to determine whether the socket is
disposed. Triggering an event or would even better. I'll give it a try.
Thanks for the idea.

Michael

"DeveloperX" <nntp...@operamail.comwrote in message

news:11**********************@y5g2000hsa.googlegro ups.com...
Adding a flag will work with exception on EndAccept() because you know
when
you close the listener socket. In other Callbacks where you have to
issue
EndReceive() there is no way of predicting when the handler socket
gets
disposed when something happens on the other side of the connection. I
also
don't see how a protected method Dispose() could be overridden in a
derived
class, or for that matter overriding the (non-virtual) Socket.Close().
That's useful to know. I'll have to check why I thought Close could be
overridden I could of sworn it was virtual, again 1.1, I'm back on 2
now but I can't imagine that would change. I don't understand what you
mean regarding to Dispose, have I missed something obvious?
This compiles:
class Socket2 : System.Net.Sockets.Socket
{
public Socket2(AddressFamily af, SocketType st, ProtocolType
pt) : base(af,st,pt)
{
}
protected override void Dispose(Boolean v)
{
Console.WriteLine("test");
base.Dispose(v);
}
}
Test is printed when I do
Socket2 s = new Socket2(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
using (s)
{
Console.WriteLine(".");
}
(silly example I know, but just trying to understand what you mean)
Cheers- Hide quoted text -

- Show quoted text -
Aah good stuff, yes I like the wrapper idea, it's certainly the
cleanest I think. Cheers Michael.
Apr 12 '07 #11

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

Similar topics

3
by: Tomaz Rotovnik | last post by:
Hi I created very simple dll (vc++) which has three functions (start, stop and initialization). it starts capturing sound from soundblaster and when the buffer is filled with the data, dll calls...
0
by: Joachim | last post by:
When closing down my server I get the following exception An unhandled exception of type 'System.InvalidOperationException' occurred in system.dll Additional information: AcceptCallback ...
1
by: scott | last post by:
Hi all hope some one can help me with this prob because it is really annoying me and I can't seem to solve it. Just like to say thx to any one that can offer any help. Ok the prob. I have a...
1
by: Chris Morse | last post by:
WARNING: Verbosity: skip to the very bottom paragraph for succinct version of my question.) Hi- I can't seem to find an answer to this. I am playing around with a variation of the ".NET...
11
by: Nuno Magalhaes | last post by:
Does anyone know why the BeginAccept doesn't work? If, in the code below, I do the normal Accept function I can get the client socket but it seems that the callback isn't really called. Here's the...
4
by: Nuno Magalhaes | last post by:
One thing I've noticed is that if I try that code on a simple form load event it works ok like this: ....form load event... Socket socket=new...
5
by: darthghandi | last post by:
I've created a class to listen to all interfaces and do a BeginAccept(). Once it gets a connection, it passes the connected socket off and stores it in a List. Next, it continues to listen for...
10
by: SQACPP | last post by:
Hi, I try to figure out how to use Callback procedure in a C++ form project The following code *work* perfectly on a console project #include "Windows.h" BOOL CALLBACK...
0
by: Tim Spens | last post by:
--- On Fri, 6/27/08, Tim Spens <t_spens@yahoo.comwrote: I think I know where the problem is but I'm unsure how to fix it. When I call Register_Handler(...) from python via...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpī 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.