C#暂停线程暂停整个应用程序



我只想用加载文本制作一个小溅起屏幕。但是,我得到的是一个白屏幕,当代码结束时启动,为什么是?

代码:

public partial class SplashScreen : Page
{
    public SplashScreen()
    {
        InitializeComponent();
    }
    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        Loading.Content = "Loading";
        Thread.Sleep(500);
        Loading.Content = "Loading.";
        Thread.Sleep(500);
        Loading.Content = "Loading..";
        Thread.Sleep(500);
        Loading.Content = "Loading...";
        Thread.Sleep(500);
//when gets to here the page can be seen, not with loading... "animation:
    }
}

xaml:

<Viewbox>
    <Grid>
        <Image x:Name="Overview_Picture" Source="/WPF_Unity;component/Images/Splash.jpg" />
        <Label HorizontalAlignment="Center" x:Name="Loading" FontSize="54" Content="Loading..." Foreground="#a09c9d" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Bottom" FontFamily="pack://application:,,,/Fonts/#Univers LT Std 57 Cn" FontWeight="Bold" Margin="0,0,0,400" /> 
    </Grid>
</Viewbox>

这是因为您在主线程上进行睡眠。我建议启动一个正在处理您的splashscreen的单独(Worker-)线程。

使用dispatchertimer对象,它是UI线程的意识,很简单。

将计时器与dispatchertimer进行比较

new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;

                this.Dispatcher.Invoke((Action)(() =>
                {
                    Loading.Content = "Loading";
                }));
            Thread.Sleep(500);
            this.Dispatcher.Invoke((Action)(() =>
            {
                Loading.Content = "Loading.";
            }));
            Thread.Sleep(500);
            this.Dispatcher.Invoke((Action)(() =>
            {
                Loading.Content = "Loading..";
            }));
            Thread.Sleep(500);
            this.Dispatcher.Invoke((Action)(() =>
            {
                Loading.Content = "Loading...";
            }));
            Thread.Sleep(500);

        }).Start();

最新更新