【问题标题】:Threading with progress bar带进度条的线程
【发布时间】:2013-11-27 18:26:54
【问题描述】:

好的,我对如何创建和管理线程有疑问。下面是一些示例代码,其中对减慢所有内容的方法调用进行了注释 (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;            
}

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

【问题讨论】:

  • 那么...你有什么问题?
  • 如何将其转换为使用线程,并继续使用进度条
  • 什么版本的 .NET?
  • Visual Studio 2012,Windows 窗体应用程序,.NET Framework 为 4.5

标签: c# multithreading winforms .net-4.5


【解决方案1】:

这是一个使用后台工作人员的粗略实现。根据需要随意调整:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多