简体   繁体   English

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

[英]C# pause thread pause whole application

I just wish to make a little splash screen with loading text. 我只想制作一个载入文本的初始屏幕。 But what I get is a white screen that launches when the code finishes, why is that? 但是我得到的是在代码完成时启动的白屏,为什么呢?

Code: 码:

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: 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>

This is because you are doing the sleeps on the main thread. 这是因为您正在主线程上进行睡眠。 I would suggest to start a seperate (worker-)thread that is handling your splashscreen. 我建议启动一个单独的(工作程序)线程来处理您的启动画面。

Use a DispatcherTimer object, it is UI thread aware and is simple. 使用DispatcherTimer对象,它可以识别UI线程并且非常简单。

Comparing Timer with DispatcherTimer 将计时器与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();

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

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