码迷,mamicode.com
首页 > Windows程序 > 详细

C#使用后台进程

时间:2014-12-02 17:32:07      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:多线程

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#使用后台进程

标签:多线程

原文地址:http://wzwyc.blog.51cto.com/6432034/1585541

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!