【问题标题】:How to use AcceptTcpClient in asynchronous method如何在异步方法中使用 AcceptTcpClient
【发布时间】:2011-04-10 04:32:00
【问题描述】:

我正在使用 C++/CLI 制作一个使用 TcpListener 的小程序,我知道 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);
}

感谢您回答我的问题:

【问题讨论】:

    标签: .net visual-studio-2010 tcp c++-cli


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2017-03-06
      • 1970-01-01
      相关资源
      最近更新 更多