Following:
Converting Action method call to async Action method call
and
The 'await' operator can only be used within an async lambda expression
I've come up with the following code:
CommandHandler.cs:
public class CommandHandler : ICommand
{
private Func<Task> _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Func<Task> action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action(); // IS THIS REALLY ASYNC? VS DOESN'T COMPLAIN
}
}
AppliedJobsViewModel.cs:
class AppliedJobsViewModel
{
private TexParser texParser;
private ObservableCollection<AppliedJob> appliedJobsCollection;
public AppliedJobsViewModel() {
// TODO:
// -- do nothing here
}
public ObservableCollection<AppliedJob> AppliedJobsCollection
{
get
{
if (appliedJobsCollection == null)
{
appliedJobsCollection = new ObservableCollection<AppliedJob>();
}
return appliedJobsCollection;
}
set
{
if (value != null)
{
appliedJobsCollection = value;
}
}
}
private ICommand _openTexClick;
public ICommand OpenTexClick
{
get
{
return _openTexClick ?? (_openTexClick = new CommandHandler(() => ReadAndParseTexFile(), () => CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true;
}
}
public async Task ReadAndParseTexFile()
{
if (texParser == null)
{
texParser = new TexParser();
}
// Read file asynchronously here
await Task.Run(() => ReadFileAndUpdateUI()); // LARGE SYNC CHUNK OF CODE
}
private void ReadFileAndUpdateUI()
{
texParser.ReadTexFile();
string[][] appliedJobsArray = texParser.getCleanTable();
// Update collection here
List<AppliedJob> appliedJobsList = createAppliedJobsListFromTable(appliedJobsArray);
appliedJobsCollection = new ObservableCollection<AppliedJob>(appliedJobsList);
}
private List<AppliedJob> createAppliedJobsListFromTable(string[][] table)
{
List<AppliedJob> jobsList = new List<AppliedJob>();
for (int i = 0; i < table.Length; i++)
{
jobsList.Add(new AppliedJob(table[i]));
}
return jobsList;
}
public ObservableCollection<AppliedJob> AppliedJobs {
get;
set;
}
}
Is the code "entirely"(from the start of the Func action) async? If yes, is it "fully" MVVM? If not, why?