为什么 ActivityIndi​​cator 在整个方法完成后改变状态?

Why ActivityIndicator changes state after entire method is completed?

我想在用户点击页面上的登录按钮后显示 ActivityIndi​​cator 对象。不幸的是,这样做有一个小问题,因为在整个方法完成后,ActivityIndi​​cator 似乎改变了状态。这是我到目前为止写的代码:

private void Login(object sender, EventArgs ev)
{
    BusyIndicator.IsVisible = true; //<- here I want to show indicator

    try
    {
        //some input validation, connection opening etc
        ConnectionHandler.OpenConnection(ServerIP, "dmg", false);


    }
    catch (Exception e)
    {
        Logging.Error(e.Message, "Connection", e);
    }
}

当我在 BusyIndicator.IsVisible = true; 之后设置断点时,应用程序绝对没有变化。但是我注意到当方法完成时会显示指示符。这是此控件的正确行为吗?

为什么我需要这个?因为现场验证和连接服务器需要一些时间,我需要向用户展示后台发生的事情。登录功能需要大约 1 秒,所以指示器显示和隐藏很快,我什至看不到任何变化。

如何在用户点击按钮后立即显示指示器?

您的问题是 Login() 方法正在 UI 线程中执行。所以,尽管设置了BusyIndicator.IsVisible = true;,线程继续执行tio获取数据的方法,所以UI没有响应。

解决方法,运行 OpenConnection 在不同的线程:

private async void Login(object sender, EventArgs ev)
{
    BusyIndicator.IsVisible = true; //<- here I want to show indicator

    try
    {
        //some input validation, connection opening etc


        await Task.Run(() => { ConnectionHandler.OpenConnection(ServerIP, "dmg", false);});
    }
    catch (Exception e)
    {
        Logging.Error(e.Message, "Connection", e);
    }
}