I am new to C#, WPF & threading too. I am working on a web application with MVC5.
I got to know that I should do invoke on dispatcher when updating the UI elements in a thread other than main thread. But i am not exactly getting to know the changes I need to do.
I have a method GetBitmapForDistributionChart which does UI updation like this.
public byte[] GetBitmapForDistributionChart(int width, int height, DistributionChartParameters disrtibutionParams)
{
// delegate control instantiation to STA Thread
return DelegateBitmapGenerationToSTAThread(() =>
{
Chart canvasChart = new Chart(languageService);
canvasChart.Width = width;
canvasChart.Height = height;
canvasChart.Measure(new Size(width, height));
canvasChart.Arrange(new Rect(0, 0, width, height));
return GenerateBitmapFromControl(canvasChart, width, height);
});
}
where definition of DelegateBitmapGenerationToSTAThread looks like this:
private byte[] DelegateBitmapGenerationToSTAThread(Func<byte[]> controlBitmapGenerator)
{
byte[] imageBinaryData = null;
Thread thread = new Thread(() =>
{
var renderer = new BitmapCreator(this.languageService);
imageBinaryData = controlBitmapGenerator();
});
//Set the thread to STA
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
//Wait for the thread to end
thread.Join();
return imageBinaryData;
}
I get an exception "Cannot use a DependencyObject that belongs to a different thread than its parent Freezable." at canvasChart.Arrange when I add the following line in Chart class:
rect.Fill = distributionParams.rangeData.ElementAt(i).barColor;
which is in main thread.
If i change the same line to something which doesn't depend on right hand side class then it works.
Like, rect.Fill = new SolidColorBrush(Colors.Red);
I am not aware on how to fix this problem.
Note: Also I get exception "The calling thread cannot access this object because a different thread owns it." when trying to do this:
rect.Fill = new SolidColorBrush(distributionParams.rangeData.ElementAt(i).barColor.Color);
distributionParams structure looks like this:
public struct DistributionParams
{
public struct RangeData
{
public string range;
public double distributionValue;
public SolidColorBrush barColor;
}
public List<RangeData> rangeData;
}
Please help me fix this problem.