c#-‘System.Net.Sockets.Socket.Dispose(bool)’由于其保护级别而无法访问
作者:互联网
编译时出现此错误.这是什么意思,我该如何解决?
‘System.Net.Sockets.Socket.Dispose(bool)’由于其保护级别而无法访问
这是我的两个文件;
Listener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Multi_con_Server
{
class Listener
{
Socket s;
public bool Listening
{
get;
private set;
}
public int Port
{
get;
private set;
}
public Listener(int port)
{
Port = port;
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start()
{
if (Listening)
return;
s.Bind(new IPEndPoint(0, Port));
s.Listen(0);
s.BeginAccept(callback, null);
Listening = true;
}
public void Stop()
{
if (!Listening)
return;
s.Close();
s.Dispose();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
void callback(IAsyncResult ar)
{
try
{
Socket s = this.s.EndAccept(ar);
if (SocketAccepted != null)
{
SocketAccepted(s);
}
this.s.BeginAccept(callback, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public delegate void SocketAccecptedHandler(Socket e);
public event SocketAccecptedHandler SocketAccepted;
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Multi_Con_C
{
class Program
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
s.Connect("127.0.0.1", 8);
s.Close();
s.Dispose();
}
}
}
解决方法:
从MSDN开始,Socket.Close()自动“释放所有关联的资源”.您可以安全地从代码中删除所有出现的Socket.Dispose().
标签:visual-studio-2008,c 来源: https://codeday.me/bug/20191031/1977687.html