嗨,有一个名为 Dlist 的主表单中的 ListView,我有一个后台工作人员来下载文件,在后台工作人员中,我如何在主表单列表视图中编辑子项“进度”?
我的代码:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(link, savepath,Dlist);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(progress_complete);
worker.ProgressChanged += new ProgressChangedEventHandler(progress_changed);
worker.RunWorkerAsync();
rivate void WorkerDoWork(string link, string savepath, ListView Dlist)
{
// Start Download
Uri url = new Uri(link);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
Int64 iSize = response.ContentLength;
Int64 iRunningByteTotal = 0;
using (System.Net.WebClient client = new System.Net.WebClient())
{
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(link)))
{
using (Stream streamLocal = new FileStream(savepath, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[256];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
//Dlist.Items[Dlist.Items.IndexOfKey(fileName)].SubItems[2].Text = iProgressPercentage.ToString();
}
streamLocal.Close();
}
streamRemote.Close();
}
}
}
这一行 (//Dlist.Items[Dlist.Items.IndexOfKey(fileName)].SubItems[2].Text = iProgressPercentage.ToString();) 是为了更新列表视图,但我一直在跨线程。