Click here to Skip to main content
14,741,306 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
Hello all,
I have a C# WPF application with a database of users. I have it so a user with the correct info can login and depending if they are an Admin or a Customer it will take them to their appropriate menu. Now I want to have a loading .gif while the program is checking the database for the users information. I was thinking I should use multi-threading but while looking into it maybe I should use backgroundworker or async and await. I am not sure which one I should use. I tried my code with backgroundworker I moved my login code to the ‘Dowork’ method but when I run the program it says that my controls are not in the correct thread.
Any ways to get this gif to work would be appreciated it here is what I have.


public partial class LoginScreen : Window
    {
        private User loginUser = new User();
        BackgroundWorker backgroundWorker = null;

        public LoginScreen()
        {
            InitializeComponent();
            txtUsername.Text = "Username";
            txtPassword.Password = "Password";
            InstantiateBackgroundWorker();
        }

        private void BtnLoginUser_Click(object sender, RoutedEventArgs e)
        {
            string username = txtUsername.Text;
            string password = txtPassword.Password;

            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                //verify and enter username.
                MessageBox.Show("Enter your username.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information);
                txtUsername.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(txtPassword.Password))
            {
                MessageBox.Show("Enter your password.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information);
                txtPassword.Focus();
                return;
            }
            else
            {
                // Start loading Gif
                LoadSpinner.Visibility = Visibility.Visible;

                // Disable login and register button.
                BtnLoginUser.IsEnabled = false;
                BtnCreateUser.IsEnabled = false;

                // Start the background worker.
                backgroundWorker.RunWorkerAsync();

                //try
                //{
                //    loginUser = SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password.ToString());

                //    if (loginUser != null)
                //    {
                //        if (txtUsername.Text == loginUser.Username && txtPassword.Password == loginUser.Password)
                //        {
                //            if (loginUser.IsAdmin == true)
                //            {
                //                Window showAdminSrc = new AdminWindow(loginUser);
                //                showAdminSrc.Show();
                //                Close();
                //            }
                //            else if (loginUser.IsAdmin == false)
                //            {
                //                Window nonAdmin = new CustomerScreen(loginUser);
                //                nonAdmin.Show();
                //                Close();
                //            }
                //            else
                //                lblInvalidText.Content = "Admin is not True or False!";
                //        }
                //        else
                //        {
                //            lblInvalidText.Visibility = Visibility.Visible;
                //        }
                //    }
                //    else
                //        lblInvalidText.Visibility = Visibility.Visible;
                //}
                //catch(Exception ex)
                //{
                //    //lblInvalidText.Visibility = Visibility.Visible;
                //    MessageBox.Show(ex.Message.ToString());
                //}
            }
        }
  private void InstantiateBackgroundWorker()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
            backgroundWorker.WorkerReportsProgress = true;
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Stop the loading
            //throw new NotImplementedException();
            LoadSpinner.Visibility = Visibility.Hidden;
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // ?? Start the loading ??
            //throw new NotImplementedException();
            string username = txtUsername.Text;
            string password = txtPassword.Password;

            try
            {
                loginUser = SQLuserAccess.UserLogin(username, password);
                if (loginUser != null)
                {
                    if (username == loginUser.Username && password == loginUser.Password)
                    {
                        if (loginUser.IsAdmin)
                        {
                            Window WindowAdminMenu = new AdminWindow(loginUser);
                            WindowAdminMenu.Show();
                            Close();
                        }
                        else if (loginUser.IsCustomer)
                        {
                            Window WindowCustomerMenu = new CustomerScreen(loginUser);
                            WindowCustomerMenu.Show();
                            Close();
                        }
                        else
                            lblInvalidText.Content = "Invalid Account Information";
                    }
                    else
                        lblInvalidText.Visibility = Visibility.Visible;
                }
                else
                    lblInvalidText.Visibility = Visibility.Visible;
            }
            catch(Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }

        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            LblWatch.Content = e.UserState.ToString();
        }
        private void LoadSpinner_MediaEnded(object sender, RoutedEventArgs e)
        {
            LoadSpinner.Position = new TimeSpan(0, 0, 1);
            LoadSpinner.Play();
        }


What I have tried:

background worker methods progress dowork n completed says from a different thread
Posted
Updated 11-Dec-18 22:05pm

1 solution

Hi, you are on right track, you could use Backgroundworker for this purpose with ease, just remember some thing while working with multithread is that, we cannot access UI elements directly from another thread.
And as entire code that's executed in Backgroundworker is in another thread we cannot access or modify them, hence when you write your logic in Backgroundworker implement logic such that we do not have to use UI elements or if its needed you can access them before i.e in your case
Quote:
string username = txtUsername.Text;
string password = txtPassword.Password;

make username & password as global variable & assign the value before
Quote:
backgroundWorker.RunWorkerAsync();


or else when using such
Quote:
lblInvalidText.Content = "Invalid Account Information";


you have to let Dispatcher (basically your UI thread) know that you are changing any of there elements, hence you need to write that code in

Dispatcher.BeginInvoke(DispatcherPriority.Send,new Action(()=>{
//your logic
});


For more information on Dispatcher you can check out this link
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900