2013-11-27 29 views
-1

好吧,我有一个如何创建和管理线程的问题。下面是一些示例代码,通过方法调用放慢了所有的注释(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;    
} 

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

+0

那么...你的问题是什么? –

+0

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

+0

.NET的哪个版本? –

回答

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