使用Thread.Sleep或Task.Delay似乎不适用于我的代码

时间:2018-09-02 16:43:31

标签: c# winforms

我正在尝试检查程序的更新。
我面临的问题是Thread.Sleep或Task.Delays被完全忽略了。
CheckUpdate(),我等待5秒钟,然后显示“登录”表单,但是在我的情况下,当我调试程序时,它首先等待5秒钟,然后如果不需要更新,它将在第一个表单中直接打开第二个表单显示一个 我尝试在代码中到处都执行Thread.Sleeps,但这只会使它更长,以显示实际的第一种形式,我尝试使用console进行调试,并使用console.writeline查看是否正确完成了睡眠,但情况确实如此与UI相关的东西无法正常工作,这就是为什么我在这里寻求帮助的原因,如果这听起来很愚蠢,并且我知道Thread.Sleep不应该使用,因为它冻结了UI,但是我一直使用的方式,我深表歉意过去,只要更新表单标签或其他任何内容,它就可以毫无问题地正常工作。

public partial class PreForm : Form
{
    public PreForm()
    {
        InitializeComponent();
        CheckRights();
    }

    private void CheckRights()
    {
        HttpWebRequest.DefaultWebProxy = new WebProxy();
        try
        {
            File.Create(@"C:\Users\Default\AppData\Local\Temp\SimpleTempFile.tmp");
        }
        catch (Exception)
        {
            MessageBox.Show("Error code : #0001.\nCheck for our knowledge base for more informations.", "Error code : #0001");
            Environment.Exit(0);
        }

        CheckUpdate();
    }

    private void CheckUpdate()
    {
        WebClient Update = new WebClient();

        if (Update.DownloadString("https://RandomSiteWithString.txt").Contains("1.1"))
        {

            TextBar.Text = "Using latest version..";
            Thread.Sleep(5000);
            Login F2 = new Login();
            F2.Show();

        }
        else
        {

            Console.WriteLine("Downloading");

            TextBar.Text = "An update is being downloaded..";

            StartDownload();

        }
    }



    private void StartDownload()
    {
        Thread thread = new Thread(() =>
        {
            Stopwatch sw = new Stopwatch();
            WebClient webClient;

            using (webClient = new WebClient())
            {
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);


                // Start the stopwatch which we will be using to calculate the download speed
                sw.Start();

                try
                {
                    // Start downloading the file
                    webClient.DownloadFileAsync(new Uri("http://siteofupdated.exe"), "XXXXX_Update.exe");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        });
        thread.Start();

    }

    // The event that will fire whenever the progress of the WebClient is changed
    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        this.BeginInvoke((MethodInvoker)delegate
        {


            // Update the progressbar percentage only when the value is not the same.
            TaskBar.Value = e.ProgressPercentage;



            // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
            TextBar.Text = string.Format("{0} MB's / {1} MB's",
                (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
                (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
        });

    }

    // The event that will trigger when the WebClient is completed
    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        this.BeginInvoke((MethodInvoker)delegate
        {

            Stopwatch sw = new Stopwatch();
            // Reset the stopwatch.
            sw.Reset();

            if (e.Cancelled == true)
            {
                MessageBox.Show("Download has been canceled.");
            }
            else
            {
                MessageBox.Show("Download completed!");
                Process.Start("XXXXXX_Update.exe");
                Environment.Exit(0);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

在构造函数完成运行之前,不会显示PreForm表单,因此您需要从那里进行对CheckRights()的调用。

最简单的方法是将事件处理程序添加到Shown事件中,然后将调用放在此处。