English 中文(简体)
查阅背景工作人员名单
原标题:Accessing ListView from backgroundworker
  • 时间:2012-04-19 11:26:52
  •  标签:
  • c#

Hi have a listView in the main forma known Dlist, i have a background workers todown a file, in the background workers how can i edit the subitem “Progress” in the main form list view ?

我的法典:

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.IndexOfKey(fileName)]。 文本 = iProgress%.ToString(); 文本是更新清单,但一是保持相互接近。

最佳回答

Why not use BackgroundWorker.ReportProgress method (see Examples section)?

问题回答

Because the backgroundworker is indeed a different thread, seperated from the UI thread you ll need to check wether an invoke is required or not for that usercontrol. Below is a bit of sourcecode I use listView1 being your Dlist..

    delegate void SetListViewItemCallBack(ListViewItem Item);
    private void AddListViewItem(ListViewItem Item)
    {
        if (this.listView1.InvokeRequired)
        {
            SetListViewItemCallBack d = new SetListViewItemCallBack(AddListViewItem);
            this.Invoke(d, new object[] { Item });
        }
        else
        {
            this.listView1.Items.Add(Item);
        }
    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        DataSet dsInfo = // whatever you want..
        for (int i = 0; i < dsInfo.Tables[0].Rows.Count; i++)
        {
            ListViewItem li = new ListViewItem();
            li.Text = dsInfo.Tables[0].Rows[i]["AXT_Tag"].ToString();
            li.Tag = dsInfo.Tables[0].Rows[i]["AXT_ID"].ToString();
            AddListViewItem(li);
        }
    }




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签