简体   繁体   English

函数在 UI 更改为可见之前运行,即使 UI 在函数运行之前设置为可见

[英]Function runs before UI gets changed to visible even though the UI was set to visible before the function was ran

Basically I have a C# WinUI3 app which has a function which runs a process, and I wanted it to make some text labels visible to show the user what the app is doing, however even though I've set the visibility as visible, it doesn't get changed until all the functions have finished running and the button just stays clicked and looks as if the app is hanging even though it hasn't.基本上我有一个 C# WinUI3 应用程序,它有一个运行进程的功能,我希望它使一些文本标签可见以向用户显示应用程序正在做什么,但是即使我将可见性设置为可见,它也不会在所有功能完成运行并且按钮保持单击状态并且看起来应用程序挂起之前,它不会被更改,即使它没有挂起。 Here's a photo of my code.这是我的代码的照片。

I have no idea where to start to fix this, I've looked up my problem and haven't seem to have found any answers so far.我不知道从哪里开始解决这个问题,我已经查看了我的问题,但到目前为止似乎还没有找到任何答案。 Sorry if I've done something wrong in my post, I'm pretty new to stack overflow抱歉,如果我在帖子中做错了什么,我对堆栈溢出还很陌生

Your UI is not updating because you're running everything in the UI thread.您的 UI 没有更新,因为您正在 UI 线程中运行所有内容。 I guess you need to learn about async / await .我想您需要了解async / await Here is a good tutorial from Stephen Cleary. 是 Stephen Cleary 的一个很好的教程。

Try this code and you'll see that the UI gets updated.试试这段代码,您会看到 UI 得到了更新。

<Button
    Click="Button_Click"
    Content="Start" />
<TextBlock
    x:Name="MessageTextBlock"
    Text="Click the button." />
private async void Button_Click(object sender, RoutedEventArgs e)
{
    // Starts running on the UI thread.
    MessageTextBlock.Text = "Running process...";
    await RunProcess();
    MessageTextBlock.Text = "Done!";
}

private async Task RunProcess()
{
    // Releases the thread that called this method, 
    // the UI thread in this case, 
    // and lets "another thread" to run this "heavy work".
    // This is why the UI thread can update the MessageTextBlock 
    // while "another thread" is doing the "heavy work".
    await Task.Run(async () =>
    {
        // heavy work.
        await Task.Delay(1000);
    });
    // Brings back the UI thread.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM