Reputation: 21
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.
Upvotes: 0
Views: 3032
Reputation: 656
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;
}
}
Upvotes: 2