我编写了以下测试,尝试使用.NET 4.5中提供的新的async / await关键字:
[Test]
public async void DefaultFilesValid()
{
LogTest(log);
var libraryTasks = new List<Task<string>>();
foreach (var def in LibrariesModel.LibraryDefinitions)
{
IViewModel viewModel = (IViewModel)ReflectionUtility.CreateNew(def.ModelType);
var libraries = def.LibraryFiles.Where(f => def.IsDefaultFile(f)).ToArray();
foreach(var library in libraries)
{
var libraryTask = LoadEmbeddedLibraryAsync(viewModel, library);
libraryTasks.Add(libraryTask);
}
}
// Wait for the results
var libraryErrors = await Task.WhenAll(libraryTasks);
var errors = libraryErrors.SelectMany(m => m);
Assert.True(!errors.Any(), String.Join(Environment.NewLine, errors));
}
private async Task<string> LoadEmbeddedLibraryAsync(IViewModel viewModel, string library)
{
return await Task.Factory.StartNew<string>(() =>
{
var libraryDef = viewModel.Library;
var libraryMessage = String.Format("The default library '{0}' of the type '{1}' ", library, libraryDef.LibraryName);
try
{
// Open the library
viewModel.Open(library, library: true);
// Check that the hash is as expected
var fileHash = libraryDef.GetDefaultFileHash(library);
var hash = viewModel.Source.GetStatewiseHashCode().ToString();
if (fileHash != hash)
return libraryMessage + String.Format("has been modified, model hash was '{0}' but '{1}' was expected.", hash, fileHash);
}
catch (Exception ex)
{
return String.Format("failed to open: {0}", ExceptionUtility.JoinExceptionMessages(ex));
}
return null;
});
}
然而,代码是同步执行的,有人可以解释一下我做错了吗?
谢谢, 亚历克斯。