从后台线程更新Progressbar

时间:2013-07-04 05:20:30

标签: c# multithreading progress-bar background-thread

以下是我的后台工作线程

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {            
            Thread t1 = new Thread(Thread1);
            t1.Start();
            Thread t2 = new Thread(Thread2);
            t2.Start();
            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;                
            }
        }

Thread1代码如下

static void Thread1()
        {
            int nofiles=0;
            int returned = checkforfolderthread(1);
            int startvalue = 0;
            int stopvalue = 5000;
            if (returned == 1)
            {
                nofiles = countfiles();
                startvalue = startvalue + (nofiles - 1) * 1000;
                stopvalue = stopvalue - startvalue;
            }
            repeat(startvalue, stopvalue,1,nofiles-1);

        }

从线程调用的函数如下

static void repeat(int ini, int fin, int threadno, int startadd)
        {
            int i, j;
            for (j = ini; j < ini + fin; j += 1000)
            {
                StringBuilder sb = new StringBuilder();                
                for (i = j; i < j + 1000; i += 100)
                {
                    WebClient wc = new WebClient();
                    string add = System.String.Format("http://www.colourlovers.com/api/colors/new?numResults=100&resultOffset={0}", i);
                    try
                    {
                        string tobeadded = wc.DownloadString(add);                        
                        sb.AppendLine();
                        sb.Append(tobeadded);
                    }

                    catch (Exception)
                    {
                        break;                        
                    }                    
                }                
                string folderpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string filename = System.String.Format("DownloadPalette\\Thread{0}\\color{1}.xml",threadno,startadd);

                string location = Path.Combine(folderpath, filename);
                File.WriteAllText(location, sb.ToString());
                startadd = startadd + 1;

            }
        }

我想要做的是在每次完成i循环后不断更新进度条。

但我无法从后台线程中运行的此函数访问进度条。

请帮帮我

4 个答案:

答案 0 :(得分:0)

你错过了这个方法..

// Back on the 'UI' thread so we can update the progress bar
    void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // The progress percentage is a property of e
        progressBar1.Value = e.ProgressPercentage;
    }

根据此参考文献:BackgroundWorker and ProgressBar demo

答案 1 :(得分:0)

答案 2 :(得分:0)

首先创建一个方法来更新progressbar(在主线程GUI上创建它):

private void UpdateBar()
{
    //your code to update
}

然后创建一个委托并将方法传递给它(此代码也适用于主线程GUI):

private delegate void UpdateProgressBarDelegate();
private UpdateProgressBarDelegate UpdateProgressBarDelegate_Object;
UpdateProgressBarDelegate_Object = new UpdateProgressBarDelegate(this.UpdateBar);

现在从另一个线程更新它:

progressbar.Invoke(UpdateProgressBarDelegate_Object);

这里我们调用delegate object,它将在GUI线程上调用UpdateBar方法,并使用安全的线程调用。

答案 3 :(得分:0)

如果您需要更新的不仅仅是进度条值,您可以调用方法并检查是否需要调用。如果要从单独的线程访问UI对象,则需要调用。

private void updateProgress(object sender, int count, int total)
{
    if (base.InvokeRequired)
    {
        base.Invoke(new ProcessCountHandler(this.updateProgress), new object[] { sender, count, total });
    }
    else if (count <= this.progressBar1.Maximum)
    {
        this.progressBar1.Value = count;
        this.CompletedCount.Text = count.ToString("N0") + " of " + total.ToString("N0");
    }
}