0

I have a hopefully quick question. I'm trying to get to grips with asynchronous code and am wondering about best practices or best utilization of it. So, if you have some code such as

public async void DoStuff() { await Task.Factory.StartNew(() => { LoadFile(); }); DoSomethingAfter(); } public void LoadFile() { StreamReader sr = new StreamReader("file.txt"); String line; while ((line = sr.ReadLine()) != null) { switch(line) { case "A": parseObjectA(line, sr); //continues with its own loop break; case "B": parseObjectB(line, sr); //continues with its own loop break; } } } //added for clarity public Object parseObjectA(String line, StreamReader sr) { Object obj = new Object(); while ((line = sr.ReadLine()) != null) { String element; String value; parseLine(line, out element, out value); switch(element) { case "name": obj.Name = value; break; case "position": { int pos = 0; Int32.TryParse(value, out pos); obj.position = pos; break; } } } return obj; } 

Is the StreamReader loop blocking the task I set up? I noticed it's taking way longer to read the files I'm sending to it than when I didn't use a task. Do the functions need to be async all the way down? Like, would the things happening in parseObject also need to be async, and the file reading need to be async? Thanks.

17
  • 3
    You're better using await sr.ReadLineAsync than spinning up an explicit compute-bound Task via StartNew() Commented Nov 16, 2017 at 7:26
  • "wondering about best practices or best utilization of it" I have bookmarked these links, I hope you'll find them as informative as I did: best practices for the busy developer, MSDN Magazine and Stephen C's blog - Task.Run etiquette Commented Nov 16, 2017 at 7:46
  • @MickyD what if LoadFiles does more than just read the files? or if there's another function in the task that gets called when LoadFile() is done? should there be async calls all the way down to get the best usage out of threading? Commented Nov 16, 2017 at 7:55
  • I'm going purely by your example. If you have another scenario post another question or update the above Commented Nov 16, 2017 at 7:59
  • 1
    await ReadLineAsync does not block. It does not even use a thread! Commented Nov 16, 2017 at 8:20

1 Answer 1

2

Use ReadAsync on FileStream to read async file

public async Task<byte[]> ReadFileAsync(string path) { using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read,FileShare.Read)) { var result = new byte[fileStream.Length]; await fileStream.ReadAsync(result, 0, (int)fileStream.Length); return result; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.