sr
我尝试在并行 for 循环中创建流读取器对象 ( )。它正在工作,但需要 1.3 分钟才能获取本应在 4 秒内获取的数据。我希望这个问题与这个StreamReader
对象有关。当尝试使用下面的代码时,我遇到了一个错误,我尝试了很多方法来解决,但目前非常卡在它上面。甚至使用并发包volatile
,ThreadStatic
和lock
。
static void Main(string[] args)
{
Task.Run(() =>
{
Thread th0 = new Thread(() => ReadAllLinesAsync(
@"C:\Users\Administrator\Desktop\Fnale mail\LineDataBackHigh.csv"));
th0.Start();
th0.Join();
watch.Stop();
Debug.Log("time=" + watch.Elapsed);
Debug.Log("Finished Task + ");
});
Debug.Log("Free Executed, Task Independent");
}
public static string[] ReadAllLinesAsync(string path)
{
ConcurrentBag<string> lines = new ConcurrentBag<string>();
// Open the FileStream with the same FileMode, FileAccess
// and FileShare as a call to File.OpenText would've done.
using (StreamReader sr = File.OpenText(path))
{
string line = String.Empty;
int k = 0;
sr8 = sr;
Thread th0 = new Thread(Fetch);
th0.Start();
th0.Join();
Debug.Log("Finished Reading2" + lines.Count);
int item = 1;
void Fetch()
{
Parallel.For(k, File.ReadLines(path).Count(), z =>
{
sr8 = sr;
Debug.Log("Executing");
lines.Add(sr8.ReadLine());
// sr.Dispose();
});
}
}
return lines.ToArray();
}
错误: