我正在尝试异步和安全地读取文件(寻求最低级别的权限)。我正在使用.NET 3.5并且无法找到一个很好的示例(所有使用async和await)。
public string GetLines()
{
var encoding = new UnicodeEncoding();
byte[] allText;
using (FileStream stream =File.Open(_path, FileMode.Open))
{
allText = new byte[stream.Length];
//something like this, but does not compile in .net 3.5
stream.ReadAsync(allText, 0, (int) allText.Length);
}
return encoding.GetString(allText);
}
问题是,如何在.net 3.5中异步执行此操作,等待操作完成并将所有行发回给调用者?
调用者可以等到操作完成,但读取必须在后台线程中进行。
调用者是一个UI线程,我正在使用.NET 3.5
答案 0 :(得分:3)
有几个选项,但最简单的方法是让此方法接受回调,然后在计算给定值时调用它。调用者需要传递回调方法来处理结果而不是阻塞方法调用:
public static void GetLines(Action<string> callback)
{
var encoding = new UnicodeEncoding();
byte[] allText;
FileStream stream = File.Open(_path, FileMode.Open);
allText = new byte[stream.Length];
//something like this, but does not compile in .net 3.5
stream.ReadAsync(allText, 0, (int)allText.Length);
stream.BeginRead(allText, 0, allText.Length, result =>
{
callback(encoding.GetString(allText));
stream.Dispose();
}, null);
}
答案 1 :(得分:1)
如果您想等到操作完成,为什么需要异步操作?
return File.ReadAllText(_path, new UnicodeEncoding());
会做的伎俩
答案 2 :(得分:0)
也许是这样的:
GetLines(string path, ()=>
{
// here your code...
});
public void GetLines(string _path, Action<string> callback)
{
var result = string.Empty;
new Action(() =>
{
var encoding = new UnicodeEncoding();
byte[] allText;
using (FileStream stream = File.Open(_path, FileMode.Open))
{
allText = new byte[stream.Length];
//something like this, but does not compile in .net 3.5
stream.Read(allText, 0, (int)allText.Length);
}
result = encoding.GetString(allText);
}).BeginInvoke(x => callback(result), null);
}