Reputation: 455
There seems to be a lot of these errors found on the forum, but I can't apply most of them on my situation..
My problem:
I have a page: PosterHome.xaml, with a uniform grid on it. In my code-behind, I have a drawthread:
drawThread = new Thread(new ThreadStart(drawPosters));
drawThread.SetApartmentState(ApartmentState.STA);
drawThread.Start();
This threadmethod (drawPosters) is occasionally woken up by another class, using a autoresetevent. I get the error in this method the moment i'm changing the uniform grid rows:
while (true)
{
waitEvent.WaitOne();
//do some calculations
// change uniform grid rows & cols
posterUniformGrid.Rows = calculatedRows; //**-> error is first thrown here**
posterUniformGird.Columns = calculatedCols;
}
How should I handle this? Thanks in advance.
Greets Daan
Upvotes: 0
Views: 2476
Reputation: 11607
You could try this :
while (true)
{
waitEvent.WaitOne();
this.InvokeEx(t => t.posterUniformGrid.Rows = calculatedRows);
this.InvokeEx(t => t.posterUniformGird.Columns = calculatedCols);
}
public static class ISynchronizeInvokeExtensions
{
public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
{
if (@this.InvokeRequired)
{
try
{
@this.Invoke(action, new object[] { @this });
}
catch { }
}
else
{
action(@this);
}
}
}
Upvotes: 0
Reputation: 24723
You're attempting to access posterUniformGrid
which was created on the UI thread from your background thread.
To avoid this, leverage the Dispatcher.
Dispatcher.Invoke(DispatcherPriority.Normal,
new Action<object[]>(SetGrid),
new object[] { calculatedRows, calculatedColumns });
Upvotes: 7