Я пытаюсь проверить наличие обновлений в моей программе.
Проблема, с которой я сталкиваюсь, заключается в том, что Thread.Sleep или Task.Delays полностью игнорируются.
В CheckUpdate()
я жду 5 секунд, прежде чем показывать форму входа в систему, но в моем случае, когда я отлаживаю программу, она ожидает ПЕРВЫЕ 5 секунд, затем, если не требуется никаких обновлений, она сразу открывает вторую форму, как только первая показанный
Я пытался сделать Thread.Sleeps повсюду в коде, это только удлиняет отображение фактической первой формы, я пытался отладить с помощью консоли и использовать console.writeline, чтобы убедиться, что сон выполнен правильно, это тот случай, когда он сделан правильно, но все Связанные с пользовательским интерфейсом вещи не работают должным образом, поэтому я ищу здесь помощь, и я прошу прощения, если это звучит глупо, и я знаю, что Thread.Sleep не следует использовать, потому что он замораживает пользовательский интерфейс, как я привык делать в прошлом он работал без проблем, просто обновляя ярлыки форм или что-то в этом роде.
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);
}
});
}
}