我正在使用使用TcpListener
的C ++ / CLI创建一个小程序,我知道AcceptTcpClient
是一个同步方法,它阻止了UI线程。如何调用此方法以便它不会阻止我的UI?这是我的代码:
TcpClient^ client = server->AcceptTcpClient();
sendConsoleResult( "Connected to Client, waiting for for instructions..." );
data = nullptr;
// Get a stream Object* for reading and writing
NetworkStream^ stream = client->GetStream();
Int32 i;
// Loop to receive all the data sent by the client.
while ( i = stream->Read( bytes, 0, bytes->Length ))
{
// Translate data bytes to a ASCII String*.
data = Encoding::ASCII->GetString( bytes, 0, i );
sendConsoleResult("[RECEIVED]: "+ data);
// Process the data then send to command processing module
data = data->ToUpper();
response = commandProcess(data)->ToUpper();
array<Byte>^msg = Encoding::ASCII->GetBytes( response );
// Send back a response.
stream->Write( msg, 0, msg->Length );
sendConsoleResult("[RESPONSE]: " + response);
}
感谢您回答我的问题:
答案 0 :(得分:2)
切换为使用TcpListener.BeginAcceptTcpClient,以及使用NetworkStream.BeginRead。这将使您的整个操作异步,而不会阻止您的用户界面线程。