0

I've been through and through the search results of this website but cant seem to find what im looking for, And the only close thread that I found never got answered. Im trying to prevent my UI from freezing when downloading files but Id like everything to work on Form Load instead of a button click or something else. Heres the code Im running with right now:

private void Form1_Load(object sender, EventArgs e)
        {
            this.Show();
            if (!IsConnectedToInternet) //user is not connected to internet
            {
                MessageBox.Show("Not connected to internet!\n Please check your connection.", settings.cheatname);
            }
            else //user is connected to internet
            {
                WebClient client = new WebClient();
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };
                var newversion = client.DownloadString(settings.versiontxt);
                var newversionparsed = int.Parse(newversion);
                if (settings.version < newversionparsed) 
                {
                 
                    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                    var stringChars = new char[8];
                    var random = new Random();
                    for (int i = 0; i < stringChars.Length; i++)
                    {
                        stringChars[i] = chars[random.Next(chars.Length)];
                    }
                    var finalString = new String(stringChars);

                    Stream[] sounds = new Stream[] {
    _2B.Properties.Resources.russian,
    _2B.Properties.Resources.byebye
};
                    Stream sound = sounds[random.Next(sounds.Length)];
                    SoundPlayer audio = new SoundPlayer(sound);
                    audio.Play();
                    //System.Threading.Thread.Sleep(2300); //<=== Testing wait theory.
                    // Downloading the new version
                    WebClient myWebClient = new WebClient();
                    myWebClient.DownloadFile(settings.loaderexe, Directory.GetCurrentDirectory() + "/" + finalString + ".exe");
                    System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "/" + finalString + ".exe");
                    Application.Exit();
                        string batchCommands = string.Empty;
                        string exeFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", string.Empty).Replace("/", "\\");
                }
                else
                {
                    Login nextForm = new Login();
                    this.Hide();
                    nextForm.ShowDialog();
                    this.Close();
                }
            }
        }
    }
}

Now I know I have to use a backgroundworker but I cant seem to get it to work im not very smart when it comes to splitting threads and stuff so the usage of a backgroundworker to me is completely new. I'd like to learn but I wanna know how it SHOULD be so I can note that for future reference. Any help would be appreciated and posted code examples on how to fix or make what I need to do possible would be great.

Russianfkr
  • 17
  • 5

1 Answers1

2

You can use Thread/ThreadPool/Task to run your download function in another thread, so the UI won't freeze.

And if your function need to update the UI, you need to use Control.Invoke method to make thread-safe UI update.

You can check this UI update to solve the problem.

And I recommend to use this code below :

   this.Invoke((MethodInvoker)delegate
    {
        textBox1.Text = newversion;  //If need to update the UI
        textBox1.Visible = false;
    });

And your code in Form1_Load would be like

Task.Run(() => //Run the method in another thread to prevent freezing UI
        {
            WebClient client = new WebClient();
            var newversion = client.DownloadString("someurl"); //time consuming method

            //other code

            this.Invoke((MethodInvoker)delegate
            {
                txtClass.Text = newversion;  //If need to update the UI
            });

            //other code
        });

Edit: It would be better in the Form_Shown event, then you can see the form :) That's adding to the illusion that it's hanging/freezing.

Edit: I've gone ahead and added what you provided and adapted to fit the progressbar, Thanks to both of you the UI doesnt freeze and I can actually see it. HOWEVER the progressbar isnt actually synced with the download, How would I be able to sync it with the download? Heres the code now:

        private void Form1_Load(object sender, EventArgs e)
        {
            Task.Run(() => //Run the method in another thread to prevent freezing UI
            {
                WebClient client = new WebClient();
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };
                var newversion = client.DownloadString(settings.versiontxt);
                var newversionparsed = int.Parse(newversion);

                this.Invoke((MethodInvoker)delegate
                {
                    bunifuCircleProgressbar1.Value =+ 1;  //If need to update the UI
                });

                if (settings.version < newversionparsed)
                {

                    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                    var stringChars = new char[8];
                    var random = new Random();
                    for (int i = 0; i < stringChars.Length; i++)
                    {
                        stringChars[i] = chars[random.Next(chars.Length)];
                    }
                    var finalString = new String(stringChars);

                    Stream[] sounds = new Stream[] {
    _2B.Properties.Resources.russian,
    _2B.Properties.Resources.byebye
};
                    Stream sound = sounds[random.Next(sounds.Length)];
                    SoundPlayer audio = new SoundPlayer(sound);
                    audio.Play();
                    //System.Threading.Thread.Sleep(2300); //<=== Testing wait theory.
                    // Downloading the new version
                    WebClient myWebClient = new WebClient();
                    myWebClient.DownloadFile(settings.loaderexe, Directory.GetCurrentDirectory() + "/" + finalString + ".exe");
                    System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "/" + finalString + ".exe");
                    Application.Exit();
                    string batchCommands = string.Empty;
                    string exeFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", string.Empty).Replace("/", "\\");
                }
                else
                {
                    Login nextForm = new Login();
                    this.Hide();
                    nextForm.ShowDialog();
                    this.Close();
                }
            });
        }
Russianfkr
  • 17
  • 5
逍遥子k
  • 177
  • 5
  • So I want to update a progressbar I have which is this ```bunifuCircleProgressbar1.Value += 1;``` Could I replace the textbox.text and the textbox stuff to adapt to the progress bar? – Russianfkr Jul 17 '20 at 02:56
  • @Russianfkr Yes, any control you want to update, you can put in that ‘’this.Invoke((MethodInvoker)delegate {})’ method. – 逍遥子k Jul 17 '20 at 02:59