I’m quite new to parallel programming and threads. I want to calculate and add series to a chart, which unfortunately is a quite time-consuming task. So I’d like to show a loading screen in the meantime:
(.NET 4.0, WPF for UI)
ShowLoadingScreen(true);
CalculateAndUpdateChart(chartControl, settings);
ShowLoadingScreen(false);
...
private void ShowLoadingScreen(bool show) { loadingScreen.IsBusy = show; }
private void CalculateAndUpdateChart(ChartControl chart, ProductSettings settings)
{
chart.SomeSettings = ...
foreach(var item in settings.Items)
{
chart.Series.Points.Add(CalculateItem(item));
...
}
}
But of course that doesn’t work. So I guess I need to update the Chart control in another thread.
ShowLoadingScreen(true);
Tash.Factory.StartNew(()=>{CalculateAndUpdateChart(chartControl, settings)});
ShowLoadingScreen(false);
However, now I get different errors, most of how I cannot access chartControl and settings from another thread.
How can I access and change UI form another thread and how to pass objects created in one thread to another? Can you please give an analogous example of what I’m trying to do?
From the non-UI thread to update a control on the UI thread, you must do:
Start here:
Build More Responsive Apps With The Dispatcher
and a little here: Beginners Guide to Threading in .NET: Part 5 of n
and a small example: Task Parallel Library: 1 of n