简体   繁体   English

在C#中异步读取文件

[英]Async File Reading in c#

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? StreamReader循环是否阻止我设置的任务? 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? 就像,parseObject中发生的事情是否也需要异步,并且文件读取需要异步吗? Thanks. 谢谢。

Use ReadAsync on FileStream to read async file 在FileStream上使用ReadAsync读取异步文件

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;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM