使用进度条进行线程处理

时间:2013-11-27 18:26:54

标签: c# multithreading winforms .net-4.5

好的,我遇到了如何创建和管理线程的问题。下面是一些示例代码,方法调用会减慢注释的所有内容(sendMail)。

部分问题是,我需要让用户收到发送邮件进度的警报。在UI线程上运行它已经使它在每个消息发送后表单不重绘的位置。更不用说我相信线程实际上会大大加快这个程序的速度。

private void btn_send_Click(object sender, EventArgs e)
{
    // Stop user from clicking send multiple times
    btn_send.Enabled = false;

    // Reset Progress Bar
    progressBar1.Value = 0;

    // Get User List
    List<string[]> mycsv = csvRead();

    //Get info for progress bar
    int total = mycsv.Count;

    // Send Message to each user
    for (int x = 0; x < total; x++)
    {
        // Visual Diplay, but not updating
        txt_percent.Text = "Sending Message " + 
            x.ToString() + " of " + total.ToString();

        //Actual send message
        //This can take up to 10 seconds PER user
        sendMail(mycsv[x][0], mycsv[x][1]); 

        // Update Progress Bar
        progressBar1.Value = (int)Math.Round(((float)x / (float)total) * 100);
    }

    // Alert user to completion
    txt_percent.Text = "Finished";

    //Allow them to send again (hopefully with new message ;)
    btn_send.Enabled = true;            
}

如何将其转换为使用线程,并继续使用进度条?

1 个答案:

答案 0 :(得分:4)

这是一个背景工作者的粗略实现。随意根据需要进行调整:

BackgroundWorker bg = new BackgroundWorker();
private void button1_Click(object sender, EventArgs e)
{
    if (bg.IsBusy) return;
    progressBar1.Value = 0;

    bg.DoWork += bg_DoWork;
    bg.ProgressChanged += bg_ProgressChanged;
    bg.RunWorkerCompleted += bg_RunWorkerCompleted;
    bg.WorkerReportsProgress = true;
    bg.RunWorkerAsync();
}

void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // Alert user to completion
    txt_percent.Text = "Finished";
}

void bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Visual Diplay, but not updating
    txt_percent.Text = e.UserState.ToString();

    progressBar1.Value = e.ProgressPercentage;
}

void bg_DoWork(object sender, DoWorkEventArgs e)
{
    //Get info for progress bar
    int total = 25;

    // Send Message to each user
    for (int x = 0; x < total; x++)
    {
        //Actual send message
        sendMail();
        bg.ReportProgress((int)Math.Round(((float)x / (float)total) * 100), "Sending Message " + x.ToString() + " of " + total.ToString());
    }

}

private void sendMail()
{
    Thread.Sleep(5000);
}