首页 > 代码库 > C#使用后台进程

C#使用后台进程

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线程的东西。

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

C#使用后台进程