BackgroundWorker problem when accessing a List in DoWork

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • schnandr

    #1

    BackgroundWorker problem when accessing a List in DoWork

    Hi,

    I have a user control which contains ListView. I copy all
    ListViewItems into a separate List<ListViewIt emcalled
    unfilteredItems .
    I am using a BackgroundWorke r to filter the ListView. When I access
    this list in the DoWork Handler I am getting an
    InvalidOperatio nException that
    the List was not created by this thread. Is there a way to solve this
    problem?


    Here some Code

    public partial class ListCtrl : UserControl
    {
    private IListCtrlFilter filter;

    private BackgroundWorke r filterWorker;

    private List<ListViewIt emunfilterdItem s = new
    List<ListViewIt em>();

    ...

    void filterWorker_Do Work(object sender, DoWorkEventArgs e)
    {

    BackgroundWorke r worker = sender as BackgroundWorke r;

    List<ListViewIt emunfiltered = e.Argument as
    List<ListViewIt em>;

    if filter;!= null)
    {
    listView.Items. Clear();
    foreach (ListViewItem item in unfiltered)
    {
    if (worker.Cancell ationPending)
    return;

    if (filter.Include (item))
    worker.ReportPr ogress(0, item);
    }
    }
    }

    void filterWorker_Pr ogressChanged(o bject sender,
    ProgressChanged EventArgs e)
    {
    listView.Items. Add(e.UserState as ListViewItem);
    }

    ...
    }

    Thanks for every hint
  • Peter Duniho

    #2
    Re: BackgroundWorke r problem when accessing a List in DoWork

    On Sat, 15 Nov 2008 23:06:09 -0800, schnandr
    <andreas.schnei der@skillworks. dewrote:
    Hi,
    >
    I have a user control which contains ListView. I copy all
    ListViewItems into a separate List<ListViewIt emcalled
    unfilteredItems .
    I am using a BackgroundWorke r to filter the ListView. When I access
    this list in the DoWork Handler I am getting an
    InvalidOperatio nException that
    the List was not created by this thread. Is there a way to solve this
    problem?
    Surely your error is complaining that the _ListView_ was not created by
    the same thread. There should be no problem accessing an instance of
    List<Tfrom a different thread than the one used to create it.

    As for addressing the problem, the most obvious solution given that you're
    using a BackgroundWorke r is to use exclusively the BackgroundWorke r events
    to access the ListView itself. For example, don't clear the list until
    the first time the ProgressChanged handler is called. Alternatively, you
    can use Control.Invoke( ) if you really feel the need (but then it begs the
    question as to why you're bothering with BackgroundWorke r :) ).

    Search this newsgroup for terms like "cross-thread exception",
    "control.invoke ", and "backgroundwork er" for more details.

    Pete

    Comment

    Working...