gpt4 book ai didi

.net - 如何在异步方法中使用 AcceptTcpClient

转载 作者:可可西里 更新时间:2023-11-01 02:41:48 25 4
gpt4 key购买 nike

我正在使用使用 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);
}

感谢您回答我的问题:

最佳答案

切换到使用 TcpListener.BeginAcceptTcpClient , 以及使用 NetworkStream.BeginRead .这将使您的整个操作异步进行,并且不会阻塞您的用户界面线程。

关于.net - 如何在异步方法中使用 AcceptTcpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5609792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com