Search code examples
c#linqwindows-phonebackgroundworker

linq to sql query in a background worker Invalid cross-thread access


This code throws a System.UnauthorizedAccessException: Invalid cross-thread access exception.

private void DoWorker(object sender,DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    using (DbContext db = new DbContext(DbContext.littreConnectionString))
    {
        if (db.DatabaseExists())
        {
            var searchResults = from dbObject in db.LDicTable
                                where dbObject.word == SearchBox.Text
                                select dbObject;
            if (!searchResults.Any())
            {
                wordExists = false;
            }
        }
    }
}

Solution

  • This is because You cannot access UI thread objects in background worker dowork method as it executes in seperate thread not in UI thread.so it is executing in different thread and you try to access UI thread object.

    You have to Store text box text in some string and use that variable in method.

    See following link for details :

    http://www.codeproject.com/Questions/623667/BackGroundWorker-Thread-issue-with-UI-Thread

    Why can't UI components be accessed from a backgroundworker?