在这段代码中,我正在尝试使用Asynchronous
同时收听多连接请如何在此代码的这一端销毁_receivedata类
class x
{
Thread t1;
int flag = 0;
string receivedPath = "yok";
public delegate void MyDelegate();
BinaryWriter writer;
private void sent_file_Load(object sender, EventArgs e)
{
t1 = new Thread(new ThreadStart(StartListening));
t1.Start();
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
}
public void StartListening()
{
byte[] bytes = new Byte[1024];
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8221);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(ipEnd);
listener.Listen(100);
if (listener.Connected)
{
allDone.Close();
}
else
{
while (true)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptConn), listener);
allDone.WaitOne();
}
}
}
catch (Exception ex)
{
}
}
public void AcceptConn(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
_receivedata rceve = new _receivedata();
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(rceve.ReceiveData), state);
flag = 0;
}
public class _receivedata
{
public void ReceiveData(IAsyncResult ar)
{
some code
//how to destroy this instance of class at the end of this void
}
}
}
当我使用此代码时,它会销毁所有类,类_receivedata和类x
public class _receivedata : IDisposable
{
public void ReceiveData(IAsyncResult ar)
{
some code
Dispose() ; //it destroy all class ,class _receivedata and class x
}
~_receivedata()
{
Dispose(false);
}
private bool isDisposed = false;
protected void Dispose(bool disposing)
{
if (disposing)
{
// Code to dispose the managed resources of the class
}
// Code to dispose the un-managed resources of the class
isDisposed = true;
this.Dispose(disposing);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
答案 0 :(得分:1)
不确定您究竟在寻找什么,但C#确实有destructors。尽管有这个名字,但这些行为更像是终结者而不是真正的析构函数(顺便说一句,在.NET中不存在)。
示例:
public class _receivedata
{
public void ReceiveData(IAsyncResult ar)
{
}
public ~ReceiveData()
{
// Finalization logic
}
}