linq到后台工作程序中的sql查询无效的跨线程访问

时间:2014-11-19 17:42:39

标签: c# linq windows-phone backgroundworker

此代码抛出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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为你无法在后台工作程序dowork方法中访问UI线程对象,因为它在不在UI线程中的单独线程中执行。因此它在不同的线程中执行,并且您尝试访问UI线程对象。

您必须将文本框文本存储在某个字符串中,并在方法中使用该变量。

有关详细信息,请参阅以下链接:

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

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