开发者

prevent a program from busy mode while working

i am making a program which sends many emails at a time and i noticed while the program is working it goes on busy mode i.e : i can not edit anything or touch anything and i made a function to show the number of successfully sent emails and the failed ones on a label so that the user can monitor the sent emails , now i got a problem the label shows the integer number after the program has done sending emails , i want to prevent that , i tried using the threading mode but failed i开发者_Python百科t . and here is the code :

int success = 0;

    private void success()
    {
        label17.Text = success.ToString();
    }

    private void sendmail()
    {
        SmtpClient client = new SmtpClient(comboBox1.Text);
        client.Credentials = new NetworkCredential(textBox6.Text, textBox7.Text);
        MailMessage message = new MailMessage();
        message.From = new MailAddress(textBox3.Text, textBox1.Text);
        message.Subject = textBox4.Text;
        message.Body = richTextBox1.Text;
        if (textBox5.Text != "")
        {
            message.Attachments.Add(new Attachment(textBox5.Text));
        }

        string bulkpath = textBox2.Text;

        foreach(string eachmail in File.ReadAllLines(bulkpath))
        {
            Thread t = new Thread(success);          // Kick off a new thread
            t.Start();  

            message.To.Add(eachmail);
            try
            {
                client.Send(message);
                success++;
            }
            catch
            {
                MessageBox.Show("One has not passed :(");
            }
            message.To.Clear();
        }

    }


Use BackgroudWorker to start a new thread and put your sendmail() completely in another thread. After use ReportProgress method to notify to Main thread about percentage completed, in your case about quantity of mails sent.

Regards.


Optionally you can simply start a new Thread which is responsible for sending the mail

Thread t = new Thread(new ThreadStart(sendMail));
t.Start();

When using the BackgroundWorker you're able to implement progress notifications and you're able to receive a callback when your action has finished in the background.

Thorsten


Those solutions provided by other guys are perfectly valid, but needs some control over Thread and BackgroundWorker i recommend you to use Asynchronous send method.

Try this :

    void Send()
    {
        SmtpClient client = new SmtpClient();
        client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
        client.SendAsync(/* METHOD's PARAMS */);
    }

    void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Error != null || e.Cancelled)
        {
            // TODO : Report error
        }
    }

hope this help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜