Skip to content

Instantly share code, notes, and snippets.

@idg10
Created September 7, 2018 06:39
Show Gist options
  • Save idg10/76999c68c4799e614f76dfe118835ba4 to your computer and use it in GitHub Desktop.
Save idg10/76999c68c4799e614f76dfe118835ba4 to your computer and use it in GitHub Desktop.
Mishandling of resources
// Excerpt from https://blogs.msdn.microsoft.com/seteplia/2018/09/05/combining-iterator-blocks-and-async-methods-in-c/
public static IEnumerable<Task<int>> ParseFile(string path)
{
if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); }
// OpenWithRetryPolicyAsync uses RetryPolicy to try to open the file more than once.
// The method throws FileNotFoundException if the file does not exists.
using (var file = OpenWithRetryPolicyAsync(path).Result)
{
using (var reader = new StreamReader(file))
{
// Let's assume that the first line contains a number of entries.
// Using int.Parse for simplicities sake
var numberOfEntries = int.Parse(reader.ReadLine());
for (int entry = 0; entry < numberOfEntries; entry++)
{
yield return ReadAndParseAsync(reader);
}
}
}
}
private static async Task<int> ReadAndParseAsync(StreamReader reader)
{
string line = await reader.ReadLineAsync();
return int.Parse(line);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment