您好,登錄后才能下訂單哦!
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);
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。