问题
This does not appear to be a duplicate of the many hundreds of other questions with the same error. I have looked at them all and have found them to be unrelated.
I am making a little note app and am trying to read files from a directory. Following the MSDN example, I have the following code, but it is giving me an Error of:
Error 1 The modifier 'async' is not valid for this item C:\Users\Jase\documents\visual studio 2012\Projects\AppNameHere\AppNameHere\DataModel\AppNameHereDataSource.cs 192 9 AppNameHere
The code I have is:
async public NotesDataSource()
{
StorageFolder documentsFolder = KnownFolders.DocumentsLibrary;
StringBuilder outputText = new StringBuilder();
IReadOnlyList<StorageFile> fileList =
await documentsFolder.GetFilesAsync();
outputText.AppendLine("Files:");
foreach (StorageFile file in fileList)
{
if (file.FileType == "txt")
{
outputText.Append(file.Name + "\n");
}
}
// lots of irrelevant code removed.
}
I don't understand what's going on here. I followed everything to a "T". Can somebody please help?
Thank you!
回答1:
Your method signature is incorrect. Look at it:
async public NotesDataSource()
Firstly, async
has to come after the access modifier IIRC.
Secondly, either you're trying to create an async constructor (which you can't do) or you're trying to write a method without a return type (which is equally invalid).
Try this:
public async Task NotesDataSource()
That's if you meant it to be a method. If you want to effectively create an async constructor (or something close to it) you'd have to use an async static method:
public static async Task<NotesDataSource> CreateInstance()
{
// Do async stuff here which fetches all the necessary data...
return new NotesDataSource(...);
}
回答2:
I think you need to place async
after public
:
public async NotesDataSource()
{
//your code here
}
来源:https://stackoverflow.com/questions/10997174/the-modifier-async-is-not-valid-for-this-item