alex mofardin

alex mofardin

  • NA
  • 1
  • 842

BackgrounWorker in Windows forms C#

Jul 23 2014 8:27 AM
Hy,I have problem with BackgroundWorker in win forms,

On first press the button everythings works well but on every future pressed the messageBox rises more times.I don't wont the progressbar but only show or not a animated gif.I put here in code a label vs picture box with gif only for testing

Thx in advanced

Alex

private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.RunWorkerAsync();
            label1.Visible = true;
        }
        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

            if (e.UserState.ToString() == "ok")
            {
                label1.Visible = false;
                MessageBox.Show(e.UserState.ToString());
                label1.Visible = true;
            }
            else if (e.UserState.ToString() == "notOk")
            {
                label1.Visible = false;
                MessageBox.Show(e.UserState.ToString());
                return;
            }
        }

        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            if (true)//here go some variable,"true" is only for test
            {
                e.Result = (string)"ok";
                backgroundWorker1.ReportProgress(0, e.Result);
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("myMail");
                mail.To.Add("myMail");

                mail.Subject = "Test Mail";
                mail.IsBodyHtml = true;
                string htmlBody;

                htmlBody = string.Format(@"test");
                mail.Body = htmlBody;
                SmtpServer.Port = 587;

                SmtpServer.Credentials = new NetworkCredential("myMail", "myPass");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
            }
            else
            {
                e.Result = (string)"notOk";
                backgroundWorker1.ReportProgress(0, e.Result);
            } 
       
        }