C#使用后台进程

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

一、定义:ide

BackgroundWorker BgWorker = new BackgroundWorker();函数

二、初始化:this

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

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

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

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

注意:不能够把BackgroundWorker的DoWork等接口进行屡次赋值,不然会形成目标函数被屡次调用的问题。正确的作法是,每次须要从新赋值的时候,都进行BgWorker = new BackgroundWorker()操做。回调函数

三、函数体实现:string

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

相关文章
相关标签/搜索