我有以下客户端侦听器将客户端传递给HandleStationClients。 HandleStationClients的构造函数启动一个Task,其他线程中的连接用于侦听。
下面的代码在主线程上运行,具有异步功能。当客户端连接下面的等待部分时,将继续并将客户端传递给新创建的HandleStationClients并挂钩事件。 通常在连接事件之后,循环将重新开始并等待await处的新连接。 问题是这个代码循环每次连接两次。因此客户端连接和HandleStationClients将被创建并且事件将被挂钩并且循环再次启动,然后继续运行相同的过程再次创建新的HandleStationClients和事件挂钩。
在处理客户端之后,等待者没有等待,而是继续第二次。事件被触发两次。我不知道什么是错的。任何人都有线索?
while (true)
{
counter += 1;
// Wait for new connection then do rest
stationsClientSocket = await stationsServerSocket.AcceptTcpClientAsync();
stationClients.Add(stationsClientSocket, 0);
Debug.WriteLine("Client toegevoegd " + counter);
HandleStationClients stationClient = new HandleStationClients(stationsClientSocket);
stationClient.ConnectionEstabilished += stationClient_ConnectionEstabilished;
stationClient.ConnectionClosed += stationClient_ConnectionClosed;
stationClient.NewDataReceived += stationClient_NewDataReceived;
}
HandleClient看起来像
class HandleStationClients
{
public HandleStationClients(TcpClient client)
{
Task.Factory.StartNew(() => { ProcessConnection(client); });
}
#region Event definitions
public delegate void NewDataReceivedEventHandler(string newData);
public event NewDataReceivedEventHandler NewDataReceived;
public delegate void ConnectionClosedEventHandler();
public event ConnectionClosedEventHandler ConnectionClosed;
public delegate void ConnectionEstabilishedEventHandler(IPEndPoint endpoint);
public event ConnectionEstabilishedEventHandler ConnectionEstabilished;
#endregion
public async void ProcessConnection(TcpClient stationsClientSocket)
{
byte[] message = new byte[1024];
int bytesRead;
NetworkStream networkStream = stationsClientSocket.GetStream();
if (this.ConnectionEstabilished != null)
{
this.ConnectionEstabilished((IPEndPoint)stationsClientSocket.Client.RemoteEndPoint);
}
while ((true))
{
bytesRead = 0;
try
{
bytesRead = await networkStream.ReadAsync(message, 0, 1024);
}
catch (Exception ex)
{
// some error hapens here catch it
Debug.WriteLine(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
if (this.NewDataReceived != null)
{
byte[] buffer = null;
string incomingMessage = encoder.GetString(message, 0, bytesRead);
this.NewDataReceived(incomingMessage);
}
}
stationsClientSocket.Close();
// Fire the disconnect Event
this.ConnectionClosed();
}
}
答案 0 :(得分:1)
在构造函数中启动任务是个坏主意。这意味着您在注册事件处理程序时正在运行任务。有一个很好的机会,有时你不会在需要被解雇之前注册一个事件。
您应该做的是等待所有事件处理器全部注册之前启动任务。您需要创建一个Start
方法来处理启动任务,并在事件注册后让代码调用它。
更新后的课程:
class HandleStationClients
{
// Added a field to store the value until the Start method
TcpClient _client;
public HandleStationClients(TcpClient client)
{
this._client = client;
// Moved the line from here...
}
public void Start()
{
// ...to here.
Task.Factory.StartNew(() => { ProcessConnection(_client); });
}
#region Event definitions
// ...
#endregion
public async void ProcessConnection(TcpClient stationsClientSocket)
{
byte[] message = new byte[1024];
int bytesRead;
NetworkStream networkStream = stationsClientSocket.GetStream();
if (this.ConnectionEstabilished != null)
{
this.ConnectionEstabilished((IPEndPoint)stationsClientSocket.Client.RemoteEndPoint);
}
while ((true))
{
bytesRead = 0;
try
{
bytesRead = await networkStream.ReadAsync(message, 0, 1024);
}
catch (Exception ex)
{
// some error hapens here catch it
Debug.WriteLine(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
if (this.NewDataReceived != null)
{
byte[] buffer = null;
string incomingMessage = encoder.GetString(message, 0, bytesRead);
this.NewDataReceived(incomingMessage);
}
}
stationsClientSocket.Close();
// Fire the disconnect Event
// I added a line to check that ConnectionClosed isn't null
if (this.ConnectionClosed != null)
{
this.ConnectionClosed();
}
}
}
然后您需要更改调用代码,如下所示。
while (true)
{
counter += 1;
// Wait for new connection then do rest
stationsClientSocket = await stationsServerSocket.AcceptTcpClientAsync();
stationClients.Add(stationsClientSocket, 0);
Debug.WriteLine("Client toegevoegd " + counter);
HandleStationClients stationClient = new HandleStationClients(stationsClientSocket);
stationClient.ConnectionEstabilished += stationClient_ConnectionEstabilished;
stationClient.ConnectionClosed += stationClient_ConnectionClosed;
stationClient.NewDataReceived += stationClient_NewDataReceived;
// Call Start manually
stationClient.Start();
}
答案 1 :(得分:0)
我将Task从构造函数移动到Start方法。问题解决了。