I've written a tcp socket prgram that working with sockets asyncoronously.
This is some part of my code:
public void main()
{
var e = new SocketAsyncEventArgs();
e.Completed += new EventHandler<SocketAsyncEventArgs>(e_Completed);
Task.Factory.StartNew(() =>
{
allDone.Reset();
mySocket.AcceptAsync(e);
allDone.WaitOne();
});
}
public void e_Completed(object sender, SocketAsyncEventArgs e)
{
var socket = (Socket)sender;
ThreadPool.QueueUserWorkItem(HandleTcpRequest, e.AcceptSocket);
e.AcceptSocket = null;
socket.AcceptAsync(e);
}
public void HandleTcpRequest(object state)
{
var mySocket = (Socket)state;
try
{
//do some codes and work with mySocket
}
catch (Exception ex)
{
}
finally
{
mySocket.Close();
mySocket.Dispose();
}
}
I've seen lots of \device\afd in process explorer in my process. I've read and searched a lot about this and found that it is related to the Ancillary Function Driver and the Transport Driver Interface. How can I resolve this handle leak?
==========> edited my code:
Edited to accept only 10 sockets in sync way.
Feel that program is more faster, but when push my finger on Ctrl+F5, find that there are more than 10 \device\afd in process explorer and when continuing too push, see more \device\afd, but lower that above code.
mySocket.Listen(10);
while (true)
{
using (Socket so = mySocket.Accept())
{
HandleTcpRequest(so);
}
}