I have a UWP app in which one of the pages needs to do three tasks - the first is to load the main content for the page (a collection of 'Binders' objects retrieved from our API) then after that load some other content which are not dependent on the first task in any way.
My page is backed with a ViewModel (I'm using the default Template10 MVVM model) and when the page is navigated to I do this in the VM OnNavigatedToAsync method:
public async override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
{
if (mode == NavigationMode.New || mode == NavigationMode.Refresh)
{
IsBusy = true; //Show progress ring
CreateServices(); //Create API service
//Download binders for board and populate ObservableCollection<Binder>
//This has a cover image and other info I want to show in the UI immediately
await PopulateBinders();
//Get files and calendar events for board
//Here I want to run this on a different thread so it does
//not stop UI from updating when PopulateBinders() is finished
await Task.WhenAll(new[]
{
PopulateBoardFiles(),
PopulateBoardEvents()
});
IsBusy = false;
await base.OnNavigatedToAsync(parameter, mode, state);
return;
}
}
So the main task is PopulateBinders() - this calls the API, returns the data and loads it into an ObservableCollection of Binder. When this has run I want the UI to update it's bindings and show the Binder objects immediately but instead it waits until the two other tasks in the WhenAll Task) have run before updating the UI. (All three of these Tasks are defined as private async Task<bool>...)
I realise I'm missing something basic here - but I thought calling a Task from an async method would allow the UI to update? Since it clearly doesn't how do I refactor this to make my page bindings update after the first method?
I tried Task.Run(() => PopulateBinders()); but it made no difference.
Instead of running it inside OnNavigatedToAsync(), run the asynchronous task when the page is already loaded since you are unintentionally "block" the app to run base.OnNavigatedToAsync() for several seconds untill Task.WhenAll finished running.
Running on loaded event in MVVM can be achieved by implementing Microsoft.Xaml.Interactivity to bind Page.Loaded event with a DelegateCommand class in your viewmodel.
XAML Page ( assuming you are using Prism as your MVVM framework )
<Page ...
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{x:Bind Path=Vm.PageLoaded}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</Page>
and inside your viewmodel:
public class PageViewModel : ... //some interface or else
{
public DelegateCommand PageLoaded;
public PageViewModel(...)
{
PageLoaded = new DelegateCommand(async () =>
{
IsBusy = true;
CreateServices();
await PopulateBinders();
await Task.WhenAll(new[]
{
PopulateBoardFiles(),
PopulateBoardEvents()
});
IsBusy = false;
});
}
}
Read more : Binding UWP Page Loading/ Loaded to command with MVVM
I hope this code will help you to update the UI as expected:
public async override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
{
if (mode == NavigationMode.New || mode == NavigationMode.Refresh)
{
IsBusy = true; //Show progress ring
CreateServices(); //Create API service
//Download binders for board and populate ObservableCollection<Binder>
//This has a cover image and other info I want to show in the UI immediately
await PopulateBinders();
await PouplateBoardData();
await base.OnNavigatedToAsync(parameter, mode, state);
return;
}
}
private async void PopulateBoardData()
{
await Task.WhenAll(new[]
{
PopulateBoardFiles(),
PopulateBoardEvents()
});
IsBusy = false;
}
Related
I bound a button to a command in the view model that triggers a long-running operation. The operation is run in a separate task. Before and after the task, a property is set to reflect it running in the UI.
My problem now is: Sometimes, when I click the button, the change of the property BEFORE the long operation runs is registered (i.e., the UI changes accordingly), but when the task finishes, it is not immediately. I have to click somewhere in the UI to make the change to be reflected.
Here is how I did it (using MVVM Light):
_longRunningOpCommand = new RelayCommand(async () => await DoLongRunningThingAsync(), CanDoLongRunningThing);
// ...
public ICommand LongRunningOpCommand { get { return _longRunningOpCommand; } }
// ...
private async Task DoLongRunningThingAsync() {
try {
IsDoingStuff = true; // triggers a PropertyChangeEvent, is bound to UI
await Task.Factory.StartNew(async () => {
await _something.DoLenghtyOperation();
}, TaskCreationOptions.LongRunning);
} finally {
IsDoingStuff = false;
}
}
Now, the UI elements update as soon as IsDoingStuff is becoming false as they should, but they are not updated when IsDoingStuff is becoming true. I have to click into the UI to have them updated.
I think I'm doing something wrong, but can't track down what.
I'm currently working on an application that calls data from a WCF service and then loads that data into an ObservableCollection(MyListOfBillsCollection). From the OC, I set my datagrid's itemsource to that collection with the example below.
ucLoading.Visibility = Visibility.Visible;
using (TruckServiceClient service = new TruckServiceClient())
{
bills = await service.GetListOfBillsAsync();
foreach (var item in bills)
{
billItem = MyListOfBillsCollection.FirstOrDefault(x => x.Id == item.Id);
if (billItem == null)
{
billItem = new ListOfBillsView();
isNew = true;
}
billItem.Code = item.StockCode;
billItem.Group = item.GroupName;
...
if (isNew)
MyListOfBillsCollection.Add(billItem);
}
}
dgFloor.ItemsSource = MyListOfBillsCollection; //Blocking UI Thread
ucLoading.Visibility = Visibility.Collapsed;
I've got an issue where, when I load that data from the OC and into my datagrid, my UI Thread gets blocked/application freezes and I need to show a 'spinner/loader' to the user that the application is loading the data.
Is it possible to load data into a datagrid and also showing-and-hiding my spinner with two diffirent UI threads? I know it must be possible, and I have done some research but I cannot get my head around it. So I'm posting my clean code(code without me trying to use Application.Current.Dispatcher) here hoping that someone can give me some headers on what to do.
I have tried Async and Await and and used my code example in a Task method that returns a Task with all the code inside and I then used a dispatcher to release the UI work from within the method to the new Thread, but my 'spinners' still will not work correctly and my window still freezes up. In the Task method, I removed the spinners and called the Show/Collapsed code from where I awaited the Task method.
I'm building an MVVM Light WPF app in Visual Studio 2015. It has a user control that contains a WindowsFormsHost with a ReportViewer for SQL Server Reporting Services local report. A button in ReportView.xaml calls a command, which in turn sends a message to the code-behind of MasterListView.xaml to generate the report.
Here's the command called by the button in ReportViewModel.cs:
public ICommand RunReportRelayCommand =>
new RelayCommand(async ()=> { await RunReport(); });
private async Task RunReport()
{
try
{
IsBusy = true;
await Task.Run(() =>
{
Messenger.Default.Send(true, "RunMasterListReport");
});
}
finally
{
IsBusy = false;
}
}
Here's the definition of IsBusy property in ReportViewModel.cs:
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set
{
if (value == _isBusy) return;
_isBusy = value;
RaisePropertyChanged();
}
}
The same view, ReportView.xaml, which contains the button calling the above command also contains the following Extended WPF Toolkit Busy Indicator:
<UserControl>
<UserControl.Resources>
<DataTemplate x:Key="MasterListViewTemplate">
<view:MasterListView />
</DataTemplate>
</UserControl.Resources>
<xctk:BusyIndicator IsBusy="{Binding IsBusy}">
<StackPanel>
<!-- Other XAML here -->
<ContentControl ContentTemplate="{StaticResource MasterListViewTemplate}" />
</StackPanel>
</xctk:BusyIndicator>
</UserControl>
Then in the MasterListView.cs code-behind, we have this:
public partial class MasterListView : UserControl
{
public MasterListView()
{
InitializeComponent();
Messenger.Default.Register<bool>(this, "RunMasterListReport", RunMasterListReport);
}
public async void RunMasterListReport(bool val)
{
await Task.Run(() =>
{
var dataSet = new DrugComplianceDataSet();
dataSet.BeginInit();
ReportViewer.ProcessingMode = ProcessingMode.Local;
ReportViewer.LocalReport.ShowDetailedSubreportMessages = true;
ReportViewer.LocalReport.DataSources.Clear();
var dataSource = new ReportDataSource
{
Name = "MasterListRandomDataSet",
Value = dataSet.MasterListRandom
};
ReportViewer.LocalReport.DataSources.Add(dataSource);
ReportViewer.LocalReport.ReportEmbeddedResource = "MasterListRandom.rdlc";
dataSet.EndInit();
var adapter = new MasterListRandomTableAdapter { ClearBeforeFill = true }
.Fill(dataSet.MasterListRandom);
Dispatcher.Invoke((MethodInvoker)(() => { ReportViewer.RefreshReport(); }));
});
}
}
However, the busy indicator doesn't trigger, though the report does show after 5 seconds or so. What am I doing wrong? Thanks.
You got a whole soup of wat in there. Things like
await Task.Run(() =>
suggest you don't really understand how async/await works. I'd step down and find some nice documentation to read. Also, you appear to be doing all your work on the UI thread.
Dispatcher.Invoke((MethodInvoker)(() => { ReportViewer.RefreshReport(); }));
You shouldn't be touching a dispatcher in a background worker unless you're updating the UI. It appears you're offloading the actual work you intend to do in a background thread (refreshing the report) on the UI thread.
Maybe your report viewer HAS to run in the UI thread. If that's so (maybe it was designed a while ago and doesn't take advantage of multitasking) there isn't much you can do about this situation. Your UI will be locked while it's processing.
If all your long-running work has to run on the UI thread, then strip out all that nonsense. Before kicking off your work, update IsBusy, then offload execution of ReportViewer.RefreshReport() onto the Dispatcher, but using a low priority DispatcherPriority, so that it runs after the UI updates and shows that it is busy. Your UI will be frozen during processing, but at least you'll give the user an indication of what's going on.
I want a loading indicator to start immediately before the execution of a method. The execution of the method involves the work of entity framework so I don't (can't) put that type of code in a new thread bc entity framework isn't thread safe. So basically in the method below, I want the first line to execute and have the UI update and then come back and execute the rest of the code. Any ideas?
public async void LoadWizard()
{
IsLoading = true; //Need the UI to update immediately
//Now lets run the rest (This may take a couple seconds)
StartWizard();
Refresh();
}
I can't do this:
public async void LoadWizard()
{
IsLoading = true; //Need the UI to update immediately
await Task.Factory.StartNew(() =>
{
//Now lets run the rest (This may take a couple seconds)
StartWizard();
Refresh(); //Load from entityframework
});
//This isn't good to do entityframework in another thread. It breaks.
}
You can invoke empty delegate on UI dispatcher with priority set to Render, so that UI process all the queued operations with equal or higher priority than Render. (UI redraws on Render dispatcher priority)
public async void LoadWizard()
{
IsLoading = true; //Need the UI to update immediately
App.Current.Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render);
//Now lets run the rest (This may take a couple seconds)
StartWizard();
Refresh();
}
Assuming your busy indicator visibility is bound to IsLoading property, you are doing "something" wrong in StartWizard or Refresh method. Your StartWizard and Refresh methods should only load data from your data source. You must not have any code that changes the state of UI in your loading methods. Here is some pseudocode..
public async void LoadWizard()
{
IsLoading = true;
StartWizard();
var efData = Refresh();
IsLoading = false;
//update values of properties bound to the view
PropertyBoundToView1 = efData.Prop1;
PropertyBoundToView2 = efData.Prop2;
}
public void StartWizard()
{
//do something with data that are not bound to the view
}
public MyData Refresh()
{
return context.Set<MyData>().FirstOrDefault();
}
I'm working on an app and I'm restructuring my code.
On my MainPage.xaml.cs I have a TextBlock and a ListBox. I have separate file (Info.cs) that handles the HttpRequest to get the information that I need to load.
The HttpRequest in Info.cs gets information from a weather API. When it gets all the information it puts the info in a ObservableCollection.. This ObservableCollection is bind to the ListBox.
Now, I'd like to update the TextBlock when the HttpRequest is finished, to show the user that all the information has been loaded.
How can I achieve this?
MainPage.xaml.cs:
WeatherInfo weatherInfo = new WeatherInfo();
weatherInfo.getTheWeatherData();
DataContext = weatherInfo;
WeatherListBox.ItemsSource = weatherInfo.ForecastList;
StatusTextBlock.Text = "Done.";
In the Info.cs I have a Dispatcher to fill the ForecastList:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ForecastList.Clear();
ForecastList = outputList;
}
What happens now is that the TextBlock instantly changes to "Done!" (doh, its Async!) but how can I change this? So it 'waits' on the ListBox to be updated? Unfortunatly there is no 'ItemsSourceChanged' event in Windows Phone.
I suggest to use the new async+await power from C# 5.0, This is actually a good practice to use async programming in WP8.
assuming you have control of getTheWeatherData() method, and that you can mark it as async method that returns Task, you will be able to call it using await modifier.
await will not block the UI, and will cause the next code lines to be executed only after the task is done.
WeatherInfo weatherInfo = new WeatherInfo();
await weatherInfo.getTheWeatherData();
DataContext = weatherInfo;
WeatherListBox.ItemsSource = weatherInfo.ForecastList;
StatusTextBlock.Text = "Done.";
Edit:
It is supported on WP 8, and on WP 7.5 through Microsoft.Bcl.Async Nuget Package
If async programming is not an option,
you can always create a callback event in WeatherInfo class that will be signaled inside getTheWeatherData(), and register to it on the UI.
One option looks as follows:
public static void DoWork(Action processAction)
{
// do work
if (processAction != null)
processAction();
}
public static void Main()
{
// using anonymous delegate
DoWork(delegate() { Console.WriteLine("Completed"); });
// using Lambda
DoWork(() => Console.WriteLine("Completed"));
}
Both DoWork() calls will end with calling the callback that is passed as a parameter.