如何在异步方法中使用AcceptTcpClient
我正在使用 C++/CLI 编写一个使用 TcpListener
的小程序,我知道 AcceptTcpClient
是一个同步方法,它会阻塞 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);
}
感谢您回答我的问题:
I am making a small program using C++/CLI that use TcpListener
, I know that AcceptTcpClient
is a synchronous method, which blocking UI thread. How can I call this method so that it won't block my UI? Here is my code:
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);
}
Thank you for answering my question:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
切换到使用 TcpListener.BeginAcceptTcpClient,以及使用 NetworkStream.BeginRead 。这将使您的整个操作异步,并且不会阻塞您的用户界面线程。
Switch to using TcpListener.BeginAcceptTcpClient, as well as using NetworkStream.BeginRead. This will make your entire operation asynchronous, and not block your user interface thread.