Reputation: 174
this code "var results.." throwing exception "The calling thread cannot access this object because a different thread owns it". LINQ query is not bad.
Please what I am doing wrong?
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();
}
EDIT:
Exception Source: "System.Data.Linq"
TargetSite: {System.Data.Linq.SqlClient.SqlNode VisitInvocation(System.Linq.Expressions.InvocationExpression)}
Upvotes: 0
Views: 925
Reputation: 180868
Move the following line of code:
DataClassesDataContext db = new DataClassesDataContext();
into your stepByStep()
method body, and then pass db
as a parameter to your doStg()
method.
bool doStg(DataClassesDataContext db)
{
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()
{
DataClassesDataContext db = new DataClassesDataContext();
Dispatcher.BeginInvoke(new Action(() => info.Text = "Step 1"), null);
if (!doStg(db)) { return false; }
Dispatcher.BeginInvoke(new Action(() => progressBar.Value = 33), null);
Dispatcher.BeginInvoke(new Action(() => info.Text = "Step 2"), null);
if (!doStg(db)) { return false; }
Dispatcher.BeginInvoke(new Action(() => progressBar.Value = 66), null);
Dispatcher.BeginInvoke(new Action(() => info.Text = "Step 3"), null);
if (!doStg(db)) { return false; }
Dispatcher.BeginInvoke(new Action(() => progressBar.Value = 100), null);
return true;
}
Upvotes: 1