Search code examples
socketstcpwindows-runtimeblockasync-await

ConnectAsync blocking UI Thread


I have simple WinRT application, that will be communicating with remote server via TCP.

In order to do that I'm creating new StreamSocket object, and connecting to remote server after clicking a proper button, like this:

private async void ConnectButtonClick(object sender, RoutedEventArgs e)
{
    StreamSocket socket = new StreamSocket();
    HostName host = new HostName("192.168.1.15");
    await socket.ConnectAsync(host, "12121");
}

The problem is that this code is blocking the UI thread. I've created simple animation, using MonoGame (couple of moving sprites) that is running on the screen continously, in order to check if UI is blocked.

The problem is, that after clicking Connect button, animation is freezing for a second, so I assume that, connecting to the server is made in the UI thread.

Should I put my whole network code into a separate thread, or is this async/await enough?

I'd like to implement a loop, that will handle incoming data (with help od DataReader), like this:

private async void ReceiveLoop()
{
    bool running = true;

    while (running)
    {
        try
        {
            uint numStrBytes = await _reader.LoadAsync(BufferSize);

            if (numStrBytes == 0)
            {
                Disconnect();
                return;
            }

            string msg = _reader.ReadString(numStrBytes);

            OnLog(string.Format("Received: {0}", msg));
            OnDataReceived(msg);
        }
        catch (Exception exception)
        {
            OnLog("Receive failed with error: " + exception.Message);

            Disconnect();
            running = false;
        }
    }
}

Sending data will be done using StoreAsync from DataWriter.

So should I put these functions into separate threads?


Solution

  • Can't you just try doing that on a background thread to see if that helps? Something like this:

    Task.Run(
        async () =>
        {
            StreamSocket socket = new StreamSocket();
            HostName host = new HostName("192.168.1.15");
            await socket.ConnectAsync(host, "12121");
        });