为什么标签文本不会立即更改?



我试图测试ModernHttpClient的速度,当我遇到以下情况时:标签没有更新,按钮也没有在下面的代码中立即被禁用(在Nexus 5x上测试),而是等待点击被处理直到结束!这是什么,是我的错误,还是一个bug,抑或是一个奇怪的"优化"功能?

Page1.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ModernClientBenchmark.Page1">
  <StackLayout>
    <Button Text="Run the test!" Clicked="OnTestClicked" x:Name="btn"></Button>
    <Label Text="here we are" x:Name="labl"/>
  </StackLayout>
</ContentPage>

Page1.xaml.cs:

public partial class Page1 : ContentPage
{
    private const int TESTQ = 3;
    public Page1()
    {
        InitializeComponent();
    }
    private async void OnTestClicked(object sender, EventArgs e)
    {
        btn.IsEnabled = false;
        var l1 = new double[TESTQ];
        var l2 = new double[TESTQ];
        for (int i = 0; i < TESTQ; i++)
        {
            Device.BeginInvokeOnMainThread(() => labl.Text = "Step " + i);
            l2[i] = (await ManagedNetworkSpeedAsync(true)).Milliseconds;
            //l1[i] = (await NativeNetworkSpeedAsync(true)).Milliseconds;
        }
        //var avg1 = l1.Sum() / TESTQ;
        //var avg2 = l2.Sum() / TESTQ;
        var a = 234;
    }
    public static async Task<TimeSpan> NativeNetworkSpeedAsync(bool secure)
    {
        using (var client = new HttpClient(new NativeMessageHandler()))
        {
            return await RunTestAsync(secure, client);
        }
    }
    public static async Task<TimeSpan> ManagedNetworkSpeedAsync(bool secure)
    {
        using (var client = new HttpClient())
        {
            return await RunTestAsync(secure, client);
        }
    }
    public static async Task<TimeSpan> RunTestAsync(bool secure, HttpClient client)
    {
        try
        {
            var start = DateTime.Now;
            for (var i = 0; i <= 1; i++)
            {
                var result = client.GetStreamAsync(secure ? "https://xamarin.com" : "http://httpbin.org/ip").Result;
                result.Dispose();
            }
            return DateTime.Now - start;
        }
        catch (Exception ex)
        {
            var a = 234;
        }
        return new TimeSpan();
    }
}

您已经在uthread上并且正在阻塞自己,您需要将您的工作放在线程池中并从那里更新UI, await Task.Run块将完成这项工作。

这将给你你所期望的结果:

private async void OnTestClicked(object sender, EventArgs e)
{
    btn.IsEnabled = false;
    var l2 = new double[TESTQ];
    await Task.Run(async () => {
        for (int i = 0; i < TESTQ; i++)
        {
            Device.BeginInvokeOnMainThread(() => labl.Text = "Step " + i);
            l2[i] = (await ManagedNetworkSpeedAsync(true)).Milliseconds;
        }
    });
    foreach (var x in l2)
    {
        System.Diagnostics.Debug.WriteLine(x);
    }
    btn.IsEnabled = true;
}

因为你正在启动一个异步操作,并且它正在与UI线程同步,所以整个标签不会改变,直到UI线程有时间执行整个更改。

这是现代应用程序的常规行为,你不想在长时间运行的操作中阻塞UI(例如,异步操作,如通过HTTP请求外部资源)。

顺便说一句,你可以在开始异步操作之前禁用你的按钮,并在完成后再次启用它。

相关内容

  • 没有找到相关文章

最新更新