C#使用多线程,推荐使用BackgroundWorker。

1、定义:

BackgroundWorker BgWorker = new BackgroundWorker();

2、初始化:

BgWorker.WorkerReportsProgress = true;  
BgWorker.DoWork += BgWorker_DoWork;    
BgWorker.ProgressChanged += BgWorker_ProgressChanged;    
BgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;

其中DoWork是线程要执行的函数。

ProgressChanged 是进度更新时的回调函数

RunWorkerCompleted 是线程执行完成时的回调函数,这个函数里面可以直接调用UI线程的东西。

注意:不可以把BackgroundWorker的DoWork等接口进行多次赋值,否则会造成目标函数被多次调用的问题。正确的做法是,每次需要重新赋值的时候,都进行BgWorker = new BackgroundWorker()操作。

3、函数体实现:

void BgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
{    
    int progress = e.ProgressPercentage;

    LabelProgress.Text = string.Format("完成{0}%", progress);  
    LabelProgress.Left = (this.Width - LabelProgress.Width) / 2;    
}

void BgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
{    
    if (PictureList.Count > 0)    
    {    
        ShowPicture(curIndex);    
    }    
    LabelProgress.Visible = false;    
}

void BgWorker_DoWork(object sender, DoWorkEventArgs e)  
{    
    List<string> picList = new List<string>();    
    string[] extList = { ".jpg", ".png" };    
    int index = 0;    
    foreach (string item in fileList)    
    {    
        if (extList.Contains(System.IO.Path.GetExtension(item).ToLower()) == true)    
        {    
            string backName = AddImageToDB(item);    
            Debug.WriteLine("ImageName:" + backName);    
            if (string.IsNullOrEmpty(backName) == false)    
                picList.Add(backName);    
        }    
        index++;    
        BgWorker.ReportProgress(100 * index / fileList.Count);    
    }    
    curIndex = PictureList.Count;    
    PictureList.AddRange(picList);    
}