Hi have a ListView in the main forma called Dlist, i have a background worker to download a file, in the background worker how can i edit the subitem “Progress” in the main form listview ?
My Code:
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();
}
}
}
this line (//Dlist.Items[Dlist.Items.IndexOfKey(fileName)].SubItems[2].Text = iProgressPercentage.ToString();) it is to update the listview but i keep getting cross thread.
Why not use BackgroundWorker.ReportProgress method (see Examples section)?
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx