This migh幫助。我有一個名爲的WorkerThread類做的工作,我們在的WorkerThread類要
static void Main(string[] args)
{
// create the background worker object
BackgroundWorker _worker = new BackgroundWorker();
// tell the background worker it can be cancelled and report progress
_worker.WorkerReportsProgress = true;
_worker.WorkerSupportsCancellation = true;
// a worker thread object where the actual work happens
WorkerThread thread = new WorkerThread();
// add our event handlers
_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread.RunWorkerCompleted);
_worker.ProgressChanged += new ProgressChangedEventHandler(thread.ProgressChanged);
_worker.DoWork += new DoWorkEventHandler(thread.DoWork);
// start the worker thread
_worker.RunWorkerAsync();
// wait for it to be completed
while(!_worker.CancellationPending)
{
// sleep for a second
Thread.Sleep(1000);
}
Console.ReadKey();
}
現在
public class WorkerThread
{
public void DoWork(object sender, DoWorkEventArgs e)
{
//get a handle on the worker that started this request
BackgroundWorker workerSender = sender as BackgroundWorker;
// loop through 10 times and report the progress back to the sending object
for(int i = 0; i < 10; i++)
{
// tell the worker that we want to report progress being made
workerSender.ReportProgress(i);
Thread.Sleep(100);
}
// cancel the thread and send back that we cancelled
workerSender.CancelAsync();
e.Cancel = true;
}
public void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Worker Done!!");
}
public void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// print out the percent changed
Console.WriteLine(e.ProgressPercentage);
}
}
我使用的是自定義類,你可以用你的類中的方法是創建背景工作者。只需修改ProgressChanged事件中的代碼即可。
你看過[msdn]上的示例(http://msdn.microsoft.com/zh-cn/library/system.componentmodel.backgroundworker.onprogresschanged.aspx)嗎? – Blorgbeard 2011-03-11 15:58:01
我有,但我不知道如何正確,以便我的列表值添加到grdiview:S – Lars 2011-03-11 16:00:05