Reputation: 9901
For some reason I cannot figure out, the code beyond my await
statement in the following code is never reached. Why?
public class FileSystemUpdateSource : IUpdateSource
{
private ObservableCollection<UpdatePackage> _packages = new ObservableCollection<UpdatePackage>();
private readonly DirectoryInfo _importDirectory = null;
public FileSystemUpdateSource(DirectoryInfo a_importDirectory)
{
#region Argument Validation
if (a_importDirectory == null)
throw new ArgumentNullException("a_importDirectory");
#endregion
_importDirectory = a_importDirectory;
Refresh();
}
public ObservableCollection<UpdatePackage> Packages
{
get { return _packages; }
}
public async void RefreshAsync()
{
var task = new Task<IEnumerable<UpdatePackage>>(CreatePackages);
var packages = await task;
// *** Code not reached ***
Packages.Clear();
Packages.AddRange(packages);
}
public void Refresh()
{
var packages = CreatePackages();
Packages.Clear();
Packages.AddRange(packages);
}
private IEnumerable<UpdatePackage> CreatePackages()
{
var packageFiles = from packageFile in _importDirectory.EnumerateFiles().AsParallel()
where FileIsZip(packageFile)
select new UpdatePackage(packageFile);
return packageFiles;
}
private bool FileIsZip(FileInfo a_file)
{
using (var fin = a_file.OpenRead())
{
byte[] firstBytes = new byte[5];
fin.Read(firstBytes, 0, 5);
if (firstBytes[0] == 80 && firstBytes[1] == 75 && firstBytes[2] == 3 && firstBytes[3] == 4 && firstBytes[4] == 20)
return true;
else
return false;
}
}
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var importRoot = ApplicationSettings.Current.GetValue("ImportRoot") as System.IO.DirectoryInfo;
IUpdateSource updateSource = new FileSystemUpdateSource(importRoot);
updateSource.RefreshAsync();
// *** Code IS reached here. ***
}
Edits
The answer thanks to add task.Start()
to my code right before the await
like so (thanks to Reed Copsey's answer):
/// <summary>
/// Refresh the list of available update packages (asynchronously).
/// </summary>
public async Task RefreshAsync()
{
var task = new Task<IEnumerable<UpdatePackage>>(CreatePackages);
task.Start();
var packages = await task;
Packages.Clear();
Packages.AddRange(packages);
}
Upvotes: 2
Views: 127
Reputation: 564323
You're creating your Task
incorrectly.
When you call new Task
, it doesn't start the task. You should use Task.Run
instead:
var task = Task.Run(CreatePackages);
This can be simplified to:
public async void RefreshAsync()
{
var packages = await Task.Run(CreatePackages);
Upvotes: 2