Question

i use background worker to call method but in return give me an Exception here is the code

private void Button_Click(object sender, RoutedEventArgs e)
    {
     BGW.RunWorkerAsync();
    }

void BGW_DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = new Drug_Class().Search(Filter);
    }

class Drug_Class
{

    public List<WorkSpaceVariable.Drug_List> Search(Expression<Func<db.Drug_Catalog, bool>> Filter)
    {
        using (db.PVDBDataContext PVDB=new PVDBDataContext ())
        {

            try
            {

                  var DQuary = from D in PVDB.Drug_Catalogs.Where(Filter)
                    select new WorkSpaceVariable.Drug_List
                    {
                        Drugs_ID = D.Drugs_ID
                    }


                   return DQuary.ToList() ;//Exception The calling thread cannot access this object because a different thread owns it.

            }

            catch (Exception E)
            {

                return null;
            }

        }


}

i don't understand why i got this Exception may any one tell me whats wrong with my code ?

Was it helpful?

Solution

The Exception that you got really explains your problem... all you need to do is to read it:

The calling thread cannot access this object because a different thread owns it.

You should hopefully know that a BackgroundWorker works on a background thread, so you should be able to work out that the two threads mentioned would be this background thread and the main UI thread.

What it means is that you cannot manipulate UI objects that were declared on (and therefore owned by) the main UI thread on any other thread.

The solution is to not manipulate UI objects from the UI thread in your background thread. Instead, just manipulate the data in the background thread and when the BackgroundWorker has finished, then update the UI element by updating the data bound collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top