ConnectAsync阻塞UI线程 [英] ConnectAsync blocking UI Thread

查看:189
本文介绍了ConnectAsync阻塞UI线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的WinRT的应用程序,将与远程服务器通过TCP进行通信。

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

在为了做到这一点,我创建新StreamSocket对象,并连接到远程服务器点击一个适当的按钮后,像这样的:

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");
}

问题是,这个code阻塞UI线程。我创建简单的动画,使用在屏幕上运行continously MonoGame(夫妇移动精灵),以检查是否UI被阻塞。

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.

问题是,点击连接按钮后,动画冻结一秒钟,所以我认为,连接到服务器在UI线程而成。

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.

我应该把我的整个网络code到一个单独的线程,或者是这个异步/等待就够了吗?

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

我想实现一个循环,将处理传入的数据(与帮助OD DataReader的),像这样的:

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;
        }
    }
}

发送数据将使用StoreAsync从DataWriter来完成。

Sending data will be done using StoreAsync from DataWriter.

所以要把我把这些功能整合到单独的线程?

So should I put these functions into separate threads?

推荐答案

你就不能尝试做上一个后台线程来看看是否有帮助?事情是这样的:

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");
    });

这篇关于ConnectAsync阻塞UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆