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

相關文章
相關標籤/搜索