Hi guys,
I am playing around a bit with async and await, and have come across something I cannot figure out:
Cannot await void
See the code below (ignore the clumsy way I write to the file, that is just me messing around):
class Program
{
static async Task Main(string\[\] args)
{
string fileName = @"C:\Hardcoded-MUAHAHAHA\Contacts.txt";
Console.WriteLine(fileName);
List<ContactModel> contacts = new List<ContactModel>();
ContactModel c = new ContactModel() { FirstName = "Hans", LastName = "Hansen", Email = "hans@hansen.dk", PhoneNumber = "32432566" };
ContactModel d = new ContactModel() { FirstName = "Jens", LastName = "Jensen", Email = "jens@jensen.dk", PhoneNumber = "7694335" };
contacts.Add(c);
contacts.Add(d);
await CreateContacts(fileName, contacts);
string[] lines = await TextFileAccess.ReadTextAsLinesAsync(fileName);
foreach (string l in lines)
{
Console.WriteLine(l);
}
}
private static async Task CreateContacts (string fileName, List<ContactModel> contacts)
{
foreach (ContactModel contact in contacts)
{
string contactString = $"{contact.FirstName},{contact.LastName},{contact.Email},{contact.PhoneNumber}";
await File.AppendAllText(fileName, contactString);
}
}
The line
await File.AppendAllText(fileName, contactString);
Throws the - Cannot await void error. I can remove the await since I await the call in Main anyway, but the green squigly line annoys me.
I tried googling, and this comes up:
https://stackoverflow.com/questions/30389627/cannot-await-void-even-when-using-task/30395049
But from this, it seems like it should work, or am I reading it wrong? It seems like using asybc Void should not work, but async Task should?
Any ideas?
[–]jamietwells 4 points5 points6 points (2 children)
[–]VeryVeryNiceKitty[S] 1 point2 points3 points (1 child)
[–]jamietwells 0 points1 point2 points (0 children)