此代碼「var results ..」拋出異常「調用線程無法訪問此對象,因爲不同的線程擁有它」。 LINQ查詢不錯。調用線程無法訪問此對象
請問我做錯了什麼?
DataClassesDataContext db = new DataClassesDataContext();
bool doStg()
{
try
{
var results = from t in db.table
select t;
//doing some things..
return true;
}
catch (Exception Exception)
{
MessageBox.Show(Exception.Message);
return false;
}
}
bool stepByStep()
{
Dispatcher.BeginInvoke(new Action(() => info.Text = "Step 1"), null);
if (!doStg()) { return false; }
Dispatcher.BeginInvoke(new Action(() => progressBar.Value = 33), null);
Dispatcher.BeginInvoke(new Action(() => info.Text = "Step 2"), null);
if (!doStg()) { return false; }
Dispatcher.BeginInvoke(new Action(() => progressBar.Value = 66), null);
Dispatcher.BeginInvoke(new Action(() => info.Text = "Step 3"), null);
if (!doStg()) { return false; }
Dispatcher.BeginInvoke(new Action(() => progressBar.Value = 100), null);
return true;
}
private void button_Click(object sender, RoutedEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
args.Result = stepByStep();
};
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
object result = args.Result;
if ((bool)result) { MessageBox.Show("Done"); }
else { MessageBox.Show("Processing stopped."); }
};
worker.RunWorkerAsync();
}
編輯:
異常源: 「將System.Data.Linq」
TargetSite:{System.Data.Linq.SqlClient.SqlNode VisitInvocation(System.Linq.Expressions.InvocationExpression )}
爲什麼你評論了大部分'doStg'? – ChaosPandion 2010-11-19 16:27:37
@Chaos:因爲它不相關。 – 2010-11-19 16:30:37
什麼是完整的例外?另外,你註釋掉的那些實際上迭代了linq查詢的位是什麼樣的? – 2010-11-19 16:32:11