こんにちは、Dlistと呼ばれるメインフォームにListViewがあります。ファイルをダウンロードするバックグラウンドワーカーがあります。バックグラウンドワーカーで、メインフォームのリストビューのサブアイテム「Progress」を編集するにはどうすればよいですか?
私のコード:
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();)リストビューを更新しますが、クロススレッドが発生し続けます。